abap 中对于字符串长度的计算一般用 strlen 函数实现。但此函数只能算出字符的个数无法计算字符串的长度,例如 'ABC你好'用此函数计算得到的值为5,显然它不是我们想要的,它的字节长度为7 。
经过研究,我写了一个函数可以实现功能代码如下:
FUNCTION YGET_CNCHAR_CHARLE.
*"----------------------------------------------------------------------
*"*"Local interface:
*" IMPORTING
*" REFERENCE(STRING) TYPE STRING 传入字符串
*" EXPORTING
*" REFERENCE(STR) TYPE STRING 返回字符串
*" REFERENCE(CHARLEN) TYPE I 返回长度
*"----------------------------------------------------------------------
DATA: w_uccp TYPE i,
w_temp(2) TYPE c,
w_left(100) TYPE c,
w_len(10) TYPE c,
s_len TYPE i
.
w_left = string.
DATA : BEGIN OF line,
text TYPE c,
END OF line,
itab LIKE TABLE OF line WITH HEADER LINE.
*DATA str TYPE string.
DO.
CALL FUNCTION 'TEXT_SPLIT'
EXPORTING
length = 2
text = w_left
IMPORTING
line = w_temp
rest = w_left.
CALL METHOD cl_abap_conv_out_ce=>uccpi
EXPORTING
char = w_temp
RECEIVING
uccp = w_uccp.
w_len = STRLEN( w_temp ).
* WRITE: /1 w_temp,
* 10 w_uccp,
* 25 w_len.
IF w_uccp > 256.
CONCATENATE str w_temp INTO str.
ENDIF.
IF w_left IS INITIAL OR sy-index > 100.
EXIT.
ENDIF.
ENDDO.
IF str IS NOT INITIAL.
DATA:t_len TYPE i.
clear : s_len,charlen.
t_len = STRLEN( string ).
s_len = STRLEN( str ).
t_len = t_len - s_len .
s_len = s_len * 2 .
charlen = t_len + s_len.
* WRITE :/,'CHARLEN=' ,charlen, 'STR= ',str.
ENDIF.
ENDFUNCTION.
"""""""""方法2
DATA: lv_str TYPE string,
lv_len TYPE i.
lv_str = 'AB中国'.
lv_len = cl_abap_list_utilities=>dynamic_output_length( lv_str ).
WRITE lv_len.