字符数据的处理
数据处理包括有连接,分割,查找子串,字串位移等。
连接字符串
将几个字符串连接起来的使用的是CONCATENATE语句。语法格式是:concatenate s1······sn into s_dest [separted by sep]
.
tips:如果目标字符的长度小于 连接的字符串,则会被截断。为避免截断可以设置目标字符类型为string ,该类型在操作过程中可以自适应长度。
separated by sep
是用于连接拼接字符串的字符,可选。
示例:
DATA: s1(17) type c value 'firstname',
s2(10) type c value 'secondname',
s3 type string,
sep(1) type c value '.'.
concatenate s1 s2 into s3.
write / s3.
concatenate s1 s2 into s3 separated by sep.
write / s3.
分割字符串
语句使用是:SPLIT语句,语法为SPLIT s_source AT sep INTO s1 ......sn.
。当分割的字串数长度不够时候最后一个字串将包括原字串最后剩余部分。为避免这种情况可以使用内表进行操作。语法为:SPLIT s_source AT sep into table itab.
这样会根据字串数目生n内内表。LOOP AT 循环输出内表的每行数据。
DATA: text type string,
itab type table of string.
text = 'ABAP is a programming language'.
SPLIT text AT space INTO TABLE itab.
LOOP AT itab INTO text.
write / text.
ENDLOOP.
查找字符串模式
SEARCH语句用于查找,SEARCH c for str.
找到了sy-subrc将返回0,找不着返回4.(SY-SUBRC = 0: 至少有一行数据 SY-SUBRC = 4: 没有数据),模式查找则可以理解为数据库中的模糊查询。
示例 | 说明 |
---|---|
str | 搜索str并忽略尾部空格 |
.str. | 不忽略尾部空格 |
*str | 以str结尾的单词 |
str* | 以str开始的单词 |
示例:SY-FDPOS表示单词出现的位置:
DATA string1(30) type c value 'this is a testing sentence.'.
write : / 'Searched', 'SY-subrc', 'SY-FDPOS'.
search string1 for 'x'.
write : / 'X' , sy-subrc under 'SY-subrc',
sy-fdpos under 'SY-FDPOS'.
search string1 for 's*'.
write : / 's*' , sy-subrc under 'SY-subrc',
sy-fdpos under 'SY-FDPOS'.
替换字符串内容
REPLACE语句,语法为:replace str1 with str2 into a s-dest [length len].
是替换第一次出现的位置,而且替换语句中没有通配符。length len
用来限制查询的长度。
ATA name1 type string .
name1 = 'test-name'.
WHILE sy-subrc = 0.
replace '-' with ' ' into name1.
ENDWHILE.
write / name1.
确定字段的长度
使用内部函数STRLEN,[compute] n = strlen( str ).
注意括号中要有空格。
DATA: text1(24) type c value 'abap language',
len1 type i.
len1 = strlen( text1 ).
write: / 'length of ', text , 'is ' ,len.
其它的操作语句
语句 | 说明 |
---|---|
SHIFT | 将字符串整体或子串进行位移 |
CONDENSE | 删除多余的空格 |
TRANSLATE | 字符转换,ABC->abc |
OVERLAY | 用一个字符串覆盖另一个字符串 |
字符串的比较
字符型的逻辑表达式用于判断两个字串之间的包含关系
表达式的列表:
表达式 | 含义 |
---|---|
s1 CO s2 | 如果s1中仅含s2,true |
s1 CN s2 | 如果s1还包含s2之外的其它字符,true |
s1 CA s2 | 如果s1包含任何一个s2之中的字符,true |
s1 NA s2 | 如果s1不包含s2的任何字符,true |
s1 CS s2 | 如果s1包含s2字符串,true |
s1 NS s2 | 如果s1中不包含s2,true |
s1 CP s2 | 如果s1中包含模式s2,true |
s1 NP s2 | 如果s1不包含模式s2,true |
DATA: s11 type string ,
s22 type string .
s11 = 'ABAP SAP'.
s22 = 'SAP'.
if s11 cs s22 .
write: / s22, 'is in position', sy-fdpos,
'of', s11, 'String'.
endif.
CP, NP
为模式比较逻辑表达式,即可以使用通配符 “*”可以用来替换任何字符,“+”替换单个字符。
其中换码字符“#”,可以用来指定大小写—#A,转回原义—#*, 比较结尾空格—#_