Add leading spaces to a string in ABAP

SAP

If you have a requirement where some strings need to be aligned at some column and these strings have a common label so the output is two columns where the label is in the first column, values in the second, you can use the following piece of code as an example to create such list.

REPORT  z_text_spaces.
DATA:
  lt_text       TYPE STANDARD TABLE OF tline INITIAL SIZE 0,
  l_spaces      TYPE i,
  l_header_size type i,
  l_spacechars(255).

CONSTANTS:
  c_header(9)  TYPE c VALUE 'Value(s):'.    " Size of the header (char10) is taken into account !!!

FIELD-SYMBOLS:
  <fs_text> TYPE tline.

l_spaces = 20.  " TAB settings
l_header_size = STRLEN( c_header ).

" Printing first line together with value label (header)
APPEND INITIAL LINE TO lt_text ASSIGNING <fs_text>.
<fs_text>-tdline = 'Value 1'.
IF l_spaces > l_header_size.
  l_spaces = l_spaces - l_header_size.
  CONCATENATE '' <fs_text>-tdline INTO <fs_text>-tdline SEPARATED BY l_spacechars(l_spaces).
  l_spaces = l_spaces + l_header_size.
ENDIF.
CONCATENATE c_header <fs_text>-tdline INTO <fs_text>-tdline RESPECTING BLANKS.

" Printing second (and further) value(s)
APPEND INITIAL LINE TO lt_text ASSIGNING <fs_text>.
<fs_text>-tdline = 'Value 2'.
CONCATENATE '' <fs_text>-tdline INTO <fs_text>-tdline SEPARATED BY l_spacechars(l_spaces).

loop AT lt_text ASSIGNING <fs_text>.
  write / <fs_text>-tdline.
ENDLOOP.

The output will then look like as on the picture below.

ABAP leading spaces

In systems where the RESPECTING BLANKS option for CONCATENATE command is not supported you can use the following piece of code

DATA:
  a TYPE string VALUE 'ABC',
  b TYPE string,
  position TYPE i VALUE 20,
  l_spacechars TYPE string.

DO 255 TIMES.
  CONCATENATE l_spacechars ` ` INTO l_spacechars.
ENDDO.

CONCATENATE l_spacechars(position) '' INTO b SEPARATED BY a.
WRITE:/ b.

Leave a Reply