Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

How to check if there is a space at the end of text?

stepniake73
Explorer
0 Kudos

I wanna check last char of string.

I don`t know why, but strlen() don`t count last char if it is a space.
Why?

How can i check, if the last letter of string is a space?

REPORT z_last_char_space.

DATA: lv_txt1 TYPE string.
DATA: lv_txt_dl TYPE i.
DATA: lv_txt_last(1) TYPE c.

lv_txt1 = 'ala ma kota '.

lv_txt_dl = strlen( lv_txt1 ).
lv_txt_dl = lv_txt_dl - 1.

lv_txt_last = lv_txt1+lv_txt_dl(1).

IF lv_txt_last EQ ' '.
  WRITE: 'yes',/.
ELSE.
  WRITE: 'no', / .
ENDIF.

WRITE: /, lv_txt_last COLOR 5.<br>
1 ACCEPTED SOLUTION

Sandra_Rossi
Active Contributor

If you use the debugger, you will see that right after 'lv_txt1 ='ala ma kota ' the variable lv_txt1 is of length 11, not 12 as you expect. It's because of the single quote which means that the trailing blanks are ignored (except in rare occasions with some specific ABAP statements). It's named a Text Field Literal in the ABAP documentation.

If you use a back tick instead, the trailing blanks are considered. It's named a String Literal in the ABAP documentation.

lv_txt1 = `ala ma kota `.
8 REPLIES 8

Sandra_Rossi
Active Contributor

If you use the debugger, you will see that right after 'lv_txt1 ='ala ma kota ' the variable lv_txt1 is of length 11, not 12 as you expect. It's because of the single quote which means that the trailing blanks are ignored (except in rare occasions with some specific ABAP statements). It's named a Text Field Literal in the ABAP documentation.

If you use a back tick instead, the trailing blanks are considered. It's named a String Literal in the ABAP documentation.

lv_txt1 = `ala ma kota `.

Thank you very much, now I know what I should do. 🙂

matt
Active Contributor

To check the last character of a string use:

DATA(last_character) = substring( val = reverse( my_string ) len = 1 ).

To check if there are trailing spaces.

IF my_string EQ condense( my_string ).

VXLozano
Active Contributor

never used it in ABAP, but "condense" does not remove spaces before AND after? In any other languages I worked with, condense removed all of them.

Sandra_Rossi
Active Contributor

Also this:

IF contains( val = my_string end = ` ` ).

and the very old way (# to escape the space coming after it so that the space is considered):

IF my_string CP '*# '.

Sandra_Rossi
Active Contributor

And for last character, this code gives the best performance:

DATA(last_character) = substring( val = my_string off = strlen( my_string ) - 1 ).

matt
Active Contributor
0 Kudos

Condense function removes before and after.

raymond_giuseppi
Active Contributor