There are multiple ways to check if a string ends with a specific substring in ABAP:
1. Using STRLEN
and Substring Extraction
DATA: lv_string TYPE string VALUE 'Hello ABAP', lv_suffix TYPE string VALUE 'ABAP', lv_length TYPE i.
lv_length = STRLEN( lv_suffix ).
IF lv_string+STRLEN( lv_string )-lv_length(lv_length) = lv_suffix. WRITE: 'String ends with ABAP'.ELSE. WRITE: 'String does not end with ABAP'.ENDIF.
Explanation:
STRLEN( lv_suffix )
→ Gets the length of the suffix.lv_string+STRLEN( lv_string )-lv_length(lv_length)
→ Extracts the last part oflv_string
and compares it withlv_suffix
.
2. Using MATCHES
Operator (ABAP 7.40+)
DATA: lv_string TYPE string VALUE 'Hello ABAP'.
IF lv_string MATCHES '.*ABAP$'. WRITE: 'String ends with ABAP'.ELSE. WRITE: 'String does not end with ABAP'.ENDIF.
Explanation:
.*ABAP$
→ Regular expression that ensures the string ends with “ABAP”.MATCHES
operator is available from ABAP 7.40.
3. Using FIND
with FROM
Parameter
DATA: lv_string TYPE string VALUE 'Hello ABAP', lv_suffix TYPE string VALUE 'ABAP', lv_pos TYPE i.
FIND lv_suffix IN lv_string FROM ( STRLEN( lv_string ) - STRLEN( lv_suffix ) + 1 ) MATCH OFFSET lv_pos.
IF sy-subrc = 0 AND lv_pos = ( STRLEN( lv_string ) - STRLEN( lv_suffix ) ). WRITE: 'String ends with ABAP'.ELSE. WRITE: 'String does not end with ABAP'.ENDIF.
Explanation:
- Finds the substring starting from the end.
- Compares its position with the expected last position.
Best Practices
Method | Best Use Case |
---|---|
Substring (STRLEN ) | Best for all ABAP versions |
MATCHES (Regex) | Simple & powerful (ABAP 7.40+) |
FIND with FROM | Useful when position matters |
If you are using ABAP 7.40 or later, the MATCHES
operator is the cleanest solution.