欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SAP ABAP字符和字符串变量隐式转换的一些规则 SAPSAP云平台SAP Cloud PlatformABAPCloud 

程序员文章站 2022-03-04 15:03:24
...

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.

 

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud 

 

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.

 

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud 

 

For the third and fourth test, the variables with char type are used to store the converted value.

 

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud 

 

According to ABAP help, the blank is padded on the left, which could be observed below:

 

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud 

 

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.

 

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud 

 

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

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

SAP ABAP字符和字符串变量隐式转换的一些规则
            
    
    
        SAPSAP云平台SAP Cloud PlatformABAPCloud