Wednesday, March 16, 2011

ABAP Tutorial - ABAP String Split Example Code

ABAP Tutorial - ABAP String Split Example Code

ABAP developers frequently work with ABAP string functions and operators in order to deal with string variables and text operations.
Splitting string operations is one of ABAP split string tasks frequently faced with.

Although when SPLIT is the topic of a conversation in ABAP, the ABAP SPLIT function comes to mind first. If there is a seperator character like comma (,) or space, ABAP SPLIT function will work great.
But recently a friend came to me, and asked me how to divide a string variable in fixed length pieces and store them in an internal table.
Then this requirement is somehow different then the SPLIT function offers.

In fact the solution is as simple as illustrated in the given sample ABAP code with using str_var+10(10) like usage.

REPORT Z_ABAP_SPLIT_EXAMPLE.

TYPES :
BEGIN OF lty_stringArray,
str TYPE CHAR15,
END OF lty_stringArray.

DATA :
ls_stringArray TYPE lty_stringArray,
lt_stringArray TYPE TABLE OF lty_stringArray.

DATA :
gv_str TYPE string,
lv_strlength TYPE i,
lv_currentpos TYPE i,
lv_remaining TYPE i,
lv_testpos TYPE i,
lv_linesize TYPE i.

lv_linesize = 15.
gv_str = 'This is an ABAP split string example demonstrating how string is splitted by a given length and stored in an internal table'.

lv_currentpos = 0.
lv_strlength = STRLEN( gv_str ).

WHILE lv_currentpos < lv_strlength.

CLEAR ls_stringArray.

lv_testpos = lv_currentpos + lv_linesize.
IF lv_testpos > lv_strlength.
lv_remaining = lv_strlength - lv_currentpos.
ls_stringArray-str = gv_str+lv_currentpos(lv_remaining).
WRITE :/ gv_str+lv_currentpos(lv_remaining).
ELSE.
ls_stringArray-str = gv_str+lv_currentpos(lv_linesize).
WRITE :/ gv_str+lv_currentpos(lv_linesize).
ENDIF.
lv_currentpos = lv_currentpos + lv_linesize.

APPEND ls_stringArray TO lt_stringArray.

ENDWHILE.

LOOP AT lt_stringArray INTO ls_stringArray.
WRITE :/ ls_stringArray-str.
ENDLOOP.

The output of this example ABAP report is as follows :

abap-string-split-sample-code

No comments:

Post a Comment