In SAP ABAP, you can check if a string begins with a specific substring using various methods:
1. Using STRLEN
+ IF
Condition
DATA: lv_string TYPE string VALUE 'ABAP Programming', lv_prefix TYPE string VALUE 'ABAP', lv_length TYPE i.
lv_length = STRLEN( lv_prefix ).
IF lv_string( lv_length ) = lv_prefix. WRITE: 'String begins with ABAP'.ELSE. WRITE: 'String does not begin with ABAP'.ENDIF.
- Extracts the first
lv_length
characters and compares them tolv_prefix
.
2. Using CS
(Contains String) Operator with OFFSET
(ABAP 7.40+)
DATA: lv_string TYPE string VALUE 'ABAP Programming'.
IF lv_string+0(* ) CS 'ABAP'. WRITE: 'String begins with ABAP'.ELSE. WRITE: 'String does not begin with ABAP'.ENDIF.
- This checks whether
'ABAP'
appears at the beginning.
3. Using MATCHES
with Regular Expressions (ABAP 7.40+)
DATA: lv_string TYPE string VALUE 'ABAP Programming'.
IF lv_string MATCHES '^ABAP.*'. WRITE: 'String begins with ABAP'.ELSE. WRITE: 'String does not begin with ABAP'.ENDIF.
^ABAP
ensures that the string starts with “ABAP”.
4. Using FIND
Statement
DATA: lv_string TYPE string VALUE 'ABAP Programming'.
FIND 'ABAP' IN lv_string POSITION sy-fdpos.IF sy-fdpos = 0. WRITE: 'String begins with ABAP'.ELSE. WRITE: 'String does not begin with ABAP'.ENDIF.
- Checks if “ABAP” is found at position
0
.
Best Practice
- Use
lv_string( lv_length ) = lv_prefix
for older ABAP versions. - Use
MATCHES
for flexible and powerful pattern matching (ABAP 7.40+).