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- Explanation: The function
STRLENgives the length of the string excluding trailing spaces.
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: 103. 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- Explanation:
cl_abap_string=>lengthis another modern way to get the length of a string.
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- Explanation: The
LENfunction counts all characters, including spaces, whileSTRLENexcludes trailing spaces.
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- Explanation:
cl_abap_char_utilities=>cr_lfadds a newline character (\r\n), which will also be counted as part of the length.
Best Practices
| Method | Best For | Handles |
|---|---|---|
STRLEN | General use (excluding trailing spaces) | String length excluding spaces |
LEN | Counting all characters, including spaces | All characters (including spaces) |
cl_abap_string=>length | Modern approach in ABAP 7.40+ | String length (class-based) |