In SAP ABAP, you can get the length of a string in various ways. The most commonly used method is the STRLEN function, but there are also other ways depending on the context.

1. Using STRLEN Function

The STRLEN function returns the length of a string, excluding trailing spaces.

DATA: lv_string TYPE string VALUE 'Hello ABAP',
lv_length TYPE i.
lv_length = STRLEN( lv_string ).
WRITE: 'Length of string: ', lv_length. " Output: 10

2. Using XSTRING for Binary Data Length

For XSTRING (binary data), the STRLEN function also works to return the number of bytes in the XSTRING.

DATA: lv_xstring TYPE xstring,
lv_length TYPE i.
lv_xstring = 'Hello ABAP'." This is a string converted to XSTRING
lv_length = STRLEN( lv_xstring ).
WRITE: 'Length of XSTRING: ', lv_length. " Output: 10

3. Using LENGTH Method for Class Objects (ABAP 7.40 and Above)

For ABAP 7.40+, you can use the LENGTH method from the class CL_ABAP_STRING.

DATA: lv_string TYPE string VALUE 'Hello ABAP',
lv_length TYPE i.
lv_length = cl_abap_string=>length( iv_value = lv_string ).
WRITE: 'Length of string: ', lv_length. " Output: 10

4. Handling String with Padding

If your string has leading or trailing spaces and you want to include them in the length, you can use the LEN function instead of STRLEN.

DATA: lv_string TYPE string VALUE 'Hello ABAP ',
lv_length TYPE i.
lv_length = LEN( lv_string ).
WRITE: 'Length of string (with spaces): ', lv_length. " Output: 15

5. Handling Multi-Line Strings (ABAP 7.40 and Above)

For multi-line strings, STRLEN will count the length including line breaks (CR/LF).

DATA: lv_string TYPE string VALUE 'Hello ABAP' && cl_abap_char_utilities=>cr_lf && 'Next Line'.
WRITE: 'Length of multi-line string: ', STRLEN( lv_string ). " Output: 23

Best Practices

MethodBest ForHandles
STRLENGeneral use (excluding trailing spaces)String length excluding spaces
LENCounting all characters, including spacesAll characters (including spaces)
cl_abap_string=>lengthModern approach in ABAP 7.40+String length (class-based)