Finding String Length in SAP ABAP (STRLEN
)
In SAP ABAP, you can determine the length of a string using different methods, depending on the data type and requirement.
1. Using STRLEN
Function
The STRLEN
function returns the number of characters in a string.
DATA: lv_string TYPE string VALUE 'SAP ABAP', lv_length TYPE i.
lv_length = STRLEN( lv_string ).
WRITE: 'Length:', lv_length. " Output: Length: 8
- Spaces count as characters.
- Works for both
STRING
andCHAR
data types.
2. Using XSTRLEN
for Binary (XSTRING
) Data
If you need the length of a binary string (XSTRING
), use XSTRLEN
.
DATA: lv_xstring TYPE xstring, lv_length TYPE i.
lv_xstring = 'A1B2C3'X. " Hexadecimal binary data
lv_length = XSTRLEN( lv_xstring ).
WRITE: 'Binary Length:', lv_length. " Output: 3 (each byte counts as 1)
- Returns the number of bytes in
XSTRING
(not characters). - Useful for handling binary files (PDF, images, etc.).
3. Handling Leading and Trailing Spaces (CONDENSE
)
If a string has extra spaces, they affect the length. Use CONDENSE
to remove them before measuring:
DATA: lv_string TYPE string VALUE ' SAP ABAP ', lv_length TYPE i.
CONDENSE lv_string.lv_length = STRLEN( lv_string ).
WRITE: 'Trimmed Length:', lv_length. " Output: Trimmed Length: 8
CONDENSE
removes leading, trailing, and multiple spaces.
4. Finding the Length of a CHAR
Field
For CHAR
data types, STRLEN
ignores trailing spaces.
DATA: lv_char TYPE char10 VALUE 'ABAP ', lv_length TYPE i.
lv_length = STRLEN( lv_char ).
WRITE: 'Length:', lv_length. " Output: Length: 4
- Even though
lv_char
is 10 characters long,STRLEN
only counts actual text.
Summary
Method | Use Case |
---|---|
STRLEN( lv_string ) | Get length of a text string (STRING , CHAR ) |
XSTRLEN( lv_xstring ) | Get length of binary (XSTRING ) data |
CONDENSE lv_string | Remove extra spaces before measuring length |