Reverse String in Abap: Complete Solution & Deep Dive Guide

a close up of a computer screen with code on it

Mastering String Reversal in ABAP: The Ultimate Guide

Reversing a string in ABAP is a fundamental task efficiently handled by the built-in REVERSE statement, which modifies the string data object in-place. For more granular control or object-oriented patterns, developers can also implement manual loops with string slicing or use the CL_ABAP_STRING_UTILITIES class.

You've just pulled a dataset from a legacy system, and the customer IDs are backward. Or perhaps you're building a new interface and the target system requires a key to be sent in reverse order for validation. It's a scenario every ABAP developer encounters: the need to flip a string, turning "stressed" into "desserts". Your first instinct might be to write a complex, multi-line loop, painstakingly moving characters one by one. This feels cumbersome, slow, and prone to off-by-one errors.

But what if the solution was far more elegant? What if ABAP, a language known for its business-oriented robustness, had a simple, powerful command to handle this in a single, readable line? This guide is your definitive resource for mastering string reversal in ABAP. We'll go beyond the basics, exploring not just the "how," but the "why" and "when," ensuring you can write efficient, clean, and maintainable code for any scenario.


What is String Reversal in the Context of ABAP?

At its core, string reversal is the process of inverting the order of characters in a given string. For example, the string 'KODIKRA', when reversed, becomes 'ARKIDOK'. In the world of SAP and ABAP development, this is more than just an academic exercise. It's a practical tool for data transformation, algorithmic problem-solving, and interfacing with diverse systems.

Unlike some general-purpose languages where string reversal might require importing a library or writing a custom function, ABAP incorporates this functionality directly into its kernel. The primary mechanism is the REVERSE statement, a keyword designed specifically for this purpose. It operates on a character-like data object (such as types C, N, and STRING) and modifies it directly in memory, a concept known as an "in-place" operation.

This in-place modification is a key characteristic of ABAP's approach. It means you don't need to declare a second variable to hold the result; the original variable is itself transformed. This design choice emphasizes efficiency, reducing memory allocation overhead, which can be critical when processing large volumes of data in an enterprise environment.

Key Technical Terms to Understand

  • Data Object: A variable in memory that holds data. In this context, a variable of type STRING or C.
  • In-Place Operation: An algorithm that transforms data without creating a new data structure to hold the result. The input is overwritten by the output.
  • Character-like Type: ABAP data types that are treated as sequences of characters, including C (fixed-length text), N (numeric text), D (date), T (time), and the dynamic-length STRING.
  • Statement: A keyword in ABAP that instructs the runtime to perform a specific action, like REVERSE, WRITE, or MOVE.

Why is Mastering String Manipulation Crucial for an ABAP Developer?

String manipulation is the bedrock of data processing in any programming language, and ABAP is no exception. In the SAP ecosystem, data is constantly moving: from user input screens (Dynpros) to the database, from one SAP system to another via RFCs or IDocs, and to external systems through APIs. The ability to effectively parse, format, and transform this data is non-negotiable for a competent developer.

Here’s why mastering a seemingly simple task like string reversal is so important:

  1. Data Transformation for Interfaces: Legacy systems or third-party applications often have peculiar data format requirements. You might need to reverse part numbers, format identification codes, or invert byte order for specific protocols. A solid grasp of string manipulation makes these integration challenges trivial.
  2. Algorithmic Problem-Solving: Many classic programming problems, often encountered in technical interviews or complex business logic, involve string manipulation. For instance, checking if a string is a palindrome (reads the same forwards and backward, like "racecar") requires reversing it and comparing it to the original.
  3. Data Masking and Anonymization: When creating test data from productive environments, you often need to anonymize sensitive information. String reversal can be a simple, reversible step in a more complex data scrambling algorithm.
  4. Code Readability and Performance: Knowing the right tool for the job is a hallmark of a senior developer. Using the built-in REVERSE statement is vastly more readable and performant than writing a manual 10-line loop. This clean code is easier to maintain and debug, saving time and resources in the long run.

Ultimately, proficiency in string handling demonstrates a deeper understanding of the ABAP language and its capabilities. It allows you to write more robust, efficient, and elegant solutions to everyday business problems within the SAP landscape.


How to Reverse a String in ABAP: The Core Methods

ABAP provides several ways to tackle string reversal, each with its own advantages. We'll explore the most common and effective methods, from the standard built-in statement to a more manual, academic approach.

Method 1: The Built-in `REVERSE` Statement (The Professional's Choice)

This is the most direct, efficient, and recommended method for reversing a string in ABAP. The REVERSE keyword is optimized at the kernel level, making it significantly faster than any manually implemented logic.

The logic is simple: you declare a character-like variable, and then you apply the REVERSE statement to it. The variable's content is then permanently altered.

Solution Code

Here is a complete, executable ABAP report that demonstrates the REVERSE statement. You can run this code in the ABAP Editor (transaction SE38).


REPORT z_kodikra_reverse_string.

*&---------------------------------------------------------------------*
*& This program is part of the exclusive kodikra.com learning curriculum.
*& It demonstrates the primary method for reversing a string in ABAP.
*&---------------------------------------------------------------------*

DATA: gv_original_string TYPE string,
      gv_palindrome      TYPE string.

START-OF-SELECTION.
  " Initialize the strings
  gv_original_string = `stressed`.
  gv_palindrome      = `racecar`.

  " --- Display original strings ---
  WRITE: / '--- KODIKRA ABAP STRING REVERSAL ---'.
  ULINE.
  WRITE: / 'Original String 1:', gv_original_string.
  WRITE: / 'Original String 2:', gv_palindrome.
  SKIP 1.

  " --- Reverse the strings in-place ---
  REVERSE gv_original_string.
  REVERSE gv_palindrome.

  " --- Display the results ---
  WRITE: / '--- AFTER REVERSE STATEMENT ---'.
  ULINE.
  WRITE: / 'Reversed String 1:', gv_original_string.
  WRITE: / 'Reversed String 2 (Palindrome):', gv_palindrome.

Code Walkthrough

  1. REPORT z_kodikra_reverse_string.: This declares a new executable program. The 'Z' or 'Y' namespace is standard for custom developments in SAP.
  2. DATA: ... TYPE string.: We declare two variables, gv_original_string and gv_palindrome, of type string. The string type is dynamic in length, making it ideal for text of unknown or variable size.
  3. START-OF-SELECTION.: This is the main event block for a report program. The code within this block is executed when the program is run.
  4. gv_original_string = `stressed`.: We assign the initial value to our first variable using the backtick character (`), which is the modern syntax for string literals.
  5. WRITE: ...: These statements are used to output text to the screen, helping us visualize the state of our variables before and after the operation.
  6. REVERSE gv_original_string.: This is the core of the solution. The ABAP runtime takes the content of gv_original_string, reverses the character order in memory, and writes the result back into the same variable. The original value (`stressed`) is overwritten with the new value (`desserts`).
  7. The final WRITE statements display the transformed strings, confirming that the operation was successful.

Execution Flow Diagram

This diagram illustrates the simple, direct flow of the REVERSE statement.

    ● Start
    │
    ▼
  ┌──────────────────────────┐
  │ DECLARE gv_string = "stressed" │
  └────────────┬─────────────┘
               │
               ▼
  ┌──────────────────────────┐
  │   Execute REVERSE gv_string  │
  └────────────┬─────────────┘
               │
               │ (In-place modification)
               ▼
  ┌──────────────────────────┐
  │ gv_string now holds "desserts" │
  └────────────┬─────────────┘
               │
               ▼
    ● End

Method 2: The Manual Loop (The Foundational Approach)

While not recommended for production code due to poor performance and verbosity, implementing a manual reversal is an excellent learning exercise. It forces you to think about string properties like length and character position (offset). This method involves iterating through the source string from end to start and building a new string character by character.

Solution Code

This example uses a DO loop and string slicing to achieve the reversal manually.


REPORT z_kodikra_manual_reverse.

*&---------------------------------------------------------------------*
*& This program from the kodikra.com curriculum shows how to manually
*& reverse a string to understand the underlying logic.
*&---------------------------------------------------------------------*

DATA: gv_source      TYPE string VALUE `sports`,
      gv_destination TYPE string,
      gv_length      TYPE i,
      gv_index       TYPE i,
      gv_char        TYPE c LENGTH 1.

START-OF-SELECTION.
  WRITE: / '--- KODIKRA MANUAL REVERSAL ---'.
  ULINE.
  WRITE: / 'Source String:', gv_source.

  " 1. Get the length of the source string
  gv_length = strlen( gv_source ).

  " 2. Set the starting index to the last character (zero-based)
  gv_index = gv_length - 1.

  " 3. Loop from the last character down to the first
  DO gv_length TIMES.
    " 3a. Get the character at the current index
    gv_char = gv_source+gv_index(1).

    " 3b. Append (concatenate) the character to the destination string
    CONCATENATE gv_destination gv_char INTO gv_destination.

    " 3c. Decrement the index to move to the previous character
    gv_index = gv_index - 1.
  ENDDO.

  SKIP 1.
  WRITE: / '--- AFTER MANUAL LOOP ---'.
  ULINE.
  WRITE: / 'Reversed String:', gv_destination.

Code Walkthrough

  1. gv_length = strlen( gv_source ).: We first use the built-in function strlen() to determine the total number of characters in our source string. For "sports", this will be 6.
  2. gv_index = gv_length - 1.: String indexing in ABAP (for slicing) is zero-based. This means the first character is at offset 0 and the last is at offset `length - 1`. So, we initialize our index to 5.
  3. DO gv_length TIMES.: We start a loop that will execute 6 times.
  4. gv_char = gv_source+gv_index(1).: This is string slicing. The syntax variable+offset(length) extracts a substring. Here, we get 1 character at the current gv_index.
    • First iteration: `gv_index` is 5, so we get 's'.
    • Second iteration: `gv_index` is 4, so we get 't'. And so on.
  5. CONCATENATE gv_destination gv_char INTO gv_destination.: We append the extracted character to our result string.
  6. gv_index = gv_index - 1.: We decrement the index to move leftwards through the source string in the next loop iteration.
  7. The loop continues until all characters have been appended in reverse order.

Manual Reversal Flow Diagram

This diagram shows the iterative logic of the manual loop approach.

      ● Start
      │
      ▼
  ┌─────────────────┐
  │  s = "sports"   │
  │  r = ""         │
  │  len = strlen(s)│
  │  idx = len - 1  │
  └────────┬────────┘
           │
           ▼
      ◆ Loop (len > 0) ?
     ╱         ╲
   Yes          No
    │           │
    ▼           ▼
  ┌─────────────────┐   ● End
  │ char = s[idx]   │
  └────────┬────────┘
           │
           ▼
  ┌─────────────────┐
  │ r = r + char    │
  └────────┬────────┘
           │
           ▼
  ┌─────────────────┐
  │ idx = idx - 1   │
  └────────┬────────┘
           │
           └───────────┐
                       │
           ┌───────────┘
           ▼
      ◆ (Loop continues)

Method 3: The Object-Oriented Way (`CL_ABAP_STRING_UTILITIES`)

For developers embracing modern, object-oriented ABAP, SAP provides a rich set of utility classes. The class CL_ABAP_STRING_UTILITIES contains a collection of helpful static methods for string manipulation, including a REVERSE method.

This approach offers better encapsulation and fits seamlessly into a class-based programming model. It's functionally equivalent to the REVERSE statement but is called as a method.

Solution Code


REPORT z_kodikra_oo_reverse.

*&---------------------------------------------------------------------*
*& From the kodikra.com advanced ABAP curriculum, this program uses
*& the object-oriented approach for string reversal.
*&---------------------------------------------------------------------*

DATA: gv_input_string  TYPE string VALUE `ABAP is powerful`.
DATA(gv_output_string) = gv_input_string. " Create a copy to modify

START-OF-SELECTION.
  WRITE: / '--- KODIKRA OO REVERSAL ---'.
  ULINE.
  WRITE: / 'Input String:', gv_input_string.

  " Use the utility class to reverse the string
  " The method modifies the variable passed to it (CHANGING parameter)
  cl_abap_string_utilities=>reverse(
    EXPORTING
      str = gv_output_string
    CHANGING
      rev = gv_output_string
  ).

  SKIP 1.
  WRITE: / '--- AFTER CLASS METHOD CALL ---'.
  ULINE.
  WRITE: / 'Reversed String:', gv_output_string.

Code Walkthrough

  1. DATA(gv_output_string) = gv_input_string.: Here we use an inline declaration (a feature of modern ABAP) to create a copy of our input string. This is because the class method will modify the variable we pass to it, and we want to preserve the original.
  2. cl_abap_string_utilities=>reverse(...): This is how you call a static method in ABAP. You use the class name (cl_abap_string_utilities), followed by the static method operator (=>), and then the method name (reverse).
  3. The method signature can be confusing. It takes an EXPORTING parameter str and a CHANGING parameter rev. In most modern systems, you can simply pass the same variable to both, and it will be reversed in-place.
  4. The result is that gv_output_string is modified directly by the method call.

When to Use Each Method: A Comparative Analysis

Choosing the right method depends on your specific context, coding standards, and performance requirements. Here's a breakdown to help you decide.

Method Pros Cons Best For
REVERSE Statement - Highest performance (kernel-level implementation)
- Extremely readable and concise (one line)
- Standard, universally understood ABAP
- Modifies the variable in-place, which might require creating a copy if the original is needed. 99% of all use cases. It's the idiomatic, professional standard for reversing a string in procedural or simple object-oriented code.
Manual Loop - Excellent for learning core programming concepts
- Offers granular control (e.g., reverse every other character)
- No reliance on built-in functions
- Significantly slower than REVERSE
- Much more verbose and harder to read
- Prone to logical errors (off-by-one, incorrect concatenation)
Educational purposes, coding challenges from the kodikra module, or very specific, non-standard reversal logic that REVERSE cannot handle.
CL_ABAP_STRING_UTILITIES - Adheres to a strict object-oriented paradigm
- Part of a standardized toolkit of helper methods
- Promotes clean, encapsulated code
- Slightly more verbose than the REVERSE statement
- Minor performance overhead compared to the native statement.
Strictly object-oriented programs where all logic, including utilities, is handled through class methods. Essential for ABAP in the Cloud environments.

Future-Proofing Your Code

As SAP moves towards the ABAP Cloud environment and Steampunk, the emphasis on using released APIs and utility classes like CL_ABAP_STRING_UTILITIES will only grow. While the classic REVERSE statement remains fully supported and highly efficient, familiarizing yourself with the class-based alternatives is a smart career move. For new developments, especially within a larger OO framework, using the utility class is often the more future-proof choice.


Frequently Asked Questions (FAQ)

1. Is the `REVERSE` statement in ABAP case-sensitive?

Yes, it is. The REVERSE statement operates on the exact character sequence. For example, reversing "Abap" will result in "papA", with the case of each character preserved in its new position.

2. What happens if I use `REVERSE` on a non-character-like data type?

You will receive a syntax error during the program check. The ABAP compiler is strongly typed and will not allow the REVERSE statement to be used on incompatible types like integers (I), packed numbers (P), or object references.

3. How does `REVERSE` handle strings with leading or trailing spaces?

Spaces are treated just like any other character. A string like " hello " will be reversed to " olleh ". The spaces at the beginning will become spaces at the end, and vice versa.

4. Can I reverse only a part of a string in ABAP?

Not directly with a single command. To reverse a substring, you would first extract the substring into a temporary variable using offset/length slicing, use the REVERSE statement on that temporary variable, and then use REPLACE or concatenation to place the reversed part back into the original string.

5. Is the manual loop method ever faster than the built-in `REVERSE`?

No. The built-in REVERSE statement is implemented in the underlying C/C++ kernel of the SAP application server. It is highly optimized and will always be orders of magnitude faster than any implementation you can write in ABAP itself. The overhead of the ABAP loop and string concatenation is significant in comparison.

6. What is the maximum length of a string that can be reversed in ABAP?

The string data type is dynamic and can hold a very large number of characters, typically limited only by the available memory in the application server's session (roll area). For all practical business purposes, there is no effective limit to the length of a string you can reverse.

7. Are there other useful utility classes for string manipulation in ABAP?

Absolutely. Besides CL_ABAP_STRING_UTILITIES, you should explore CL_ABAP_CHAR_UTILITIES, which contains useful constants like horizontal tab or newline characters, and CL_SCS_STRING_HELPER for more advanced functionalities. Regular expressions via the FIND and REPLACE statements also offer incredibly powerful string processing capabilities.


Conclusion: From Reversed Strings to Forward-Thinking Code

We've journeyed from a simple problem—flipping a string—to a deep understanding of the tools ABAP provides. You now know that the elegant, one-line REVERSE statement is your primary tool, offering unmatched performance and readability. You've also seen the underlying logic through a manual loop and explored the modern, object-oriented approach with CL_ABAP_STRING_UTILITIES.

Mastering this fundamental skill is a stepping stone. It builds a foundation for tackling more complex data transformations and algorithmic challenges you'll face in your career as an SAP developer. Clean, efficient, and knowledgeable code is what separates a good developer from a great one.

Disclaimer: This guide is based on modern ABAP syntax (ABAP 7.40 and higher). The core REVERSE statement is available in all versions of ABAP, but inline declarations and class-based methods may not be present in older SAP systems. Always develop with your target system's version in mind.

Ready to apply your knowledge and tackle the next challenge? Continue your learning journey with the ABAP Learning Path on kodikra.com or dive deeper into the language with our complete ABAP language guide for more expert tutorials.


Published by Kodikra — Your trusted Abap learning resource.