One new colleague in my team asked me that some code does not work as he expected.
The confuse could be summarized into following source code:

DATA: lv_i  TYPE int4 VALUE 1,
      lv_s  TYPE string,
      lv_s2 TYPE string VALUE '1',
      lv_ss TYPE sstring,
      lv_s3 TYPE char18.

lv_s = lv_i.
lv_ss = lv_i.
lv_s3 = lv_i.
WRITE:/ strlen( lv_s ). 
WRITE:/ strlen( lv_s2 ).
WRITE:/ strlen( lv_ss ).
WRITE:/ strlen( lv_s3 ).
Can you get the correct answer without hesitation? 🙂
The answer is: 2, 1, 19, 17, which confuses my colleague a lot.
The reason for first result 2:
According to ABAP help, when an integer value is converted to a string value, a blank character is automatically inserted to the last place and this space is also taken into consideration for result length.

In debugger we can observe this space in Hexadecimal value view so this is the reason why we get 2 and 1 for first two strlen.

For the third and fourth test, the variables with char type are used to store the converted value.
According to ABAP help, the blank is padded on the left, which could be observed below:

Although we can still observe the existence of trailing space character in debugger, why for these two variables, the last character is not considered by strlen?
Again the answer is in help, simply because char data object with fixed length will ignore it but String type will count.

So my suggestion to my new colleagues when they meet with “weird” behavior in ABAP: always check with ABAP help first 🙂

To report this post you need to login first.

2 Comments

You must be Logged on to comment or reply to a post.

  1. Sandra Rossi

    Note: lv_ss TYPE sstring is a false friend, as “SSTRING” is a data element of type 20 characters, but “SSTRING” is best known for being a predefined DDIC data type which has a maximum length of 1333 characters, but is represented internally in ABAP by a STRING abap type (without length restriction).

    (0) 
  2. Jerry Wang Post author

    Hello Rossi,

    Thanks a lot for your comment! Yes I know that SSTRING is a data element of type 20 char:

    Would you please kindly elaborate a little bit more about this “but “SSTRING” is best known for being a predefined DDIC data type which has a maximum length of 1333 characters“?

    Yes I have created a test structure with one field of DDIC data type SSTRING:

    And I use the following code to test:

    data: lv TYPE sstring.
    CONSTANTS: cv TYPE char10 value '1234567890'.
    
    lv = '01234567890123456789ABC'.
    
    data: ls TYPE ZTEST_STRUCTURE.
    
    ls-test_id = cv.
    
    DO 300 TIMES.
       ls-test_id = ls-test_id && cv.
    ENDDO.

    And you are right, through testing I find there is no length restriction on this field.
    I am just curious how you get the maximum length of 1333? 🙂 Hope I can learn some new stuff…

    Thanks a lot!

    Best regards,
    Jerry

    (0) 

Leave a Reply