Thursday, September 11, 2008

Insert separator in a string after specified position

By Joyjit Ghosh,
Kolkata, India.


Code:

*&---------------------------------------------------------------------*
*& Report Z_DEMO_JG
*&
*&---------------------------------------------------------------------*
*&
*& Insert separator in a string after specified position
*&---------------------------------------------------------------------*

REPORT z_demo_jg.

* Data declaration

DATA: l_char1(3) TYPE c.

DATA: l_char TYPE string.

DATA: l_pos TYPE i.

DATA: l_len TYPE i.

DATA: l_len1 TYPE i.

* Selection screen

PARAMETERS: l_srt(255) TYPE c DEFAULT `12344566` obligatory, " String

l_spch(1) type c DEFAULT `,` obligatory, " Separator

l_no type int3 DEFAULT 1 obligatory. " No of places

* Length of the string

l_len = STRLEN( l_srt ).

* Divide the length by 3

l_len1 = l_len DIV l_no.

l_pos = 0.

DO l_len1 TIMES.

* Storing next l_no chars

l_char1 = l_srt+l_pos(l_no).

* Add separator with it

CONCATENATE l_char l_char1 l_spch INTO l_char.

l_pos = l_pos + l_no.

ENDDO.

* Check remaining length

l_len1 = l_len - l_pos.

IF l_len1 > 0.

* Storing remaining characters

l_char1 = l_srt+l_pos(l_len1).

CONCATENATE l_char l_char1 INTO l_char.

ENDIF.

CONDENSE l_char NO-GAPS.

* Display original string

write /.

WRITE : 'Original String:',

l_srt.

l_srt = l_char.

* Display modified string

write /.

WRITE : 'Modified String :',

l_srt.

.

Selection screen:


Output:


No comments: