
TCL基础教程——(4)字符串处理
对于任何一种脚本语言来说,强大的字符串处理功能都是为人们所津津乐道的,TCL也不例外,那么究竟TCL的字符串处理有什么功能呢?下面将介绍简单模式匹配,在日后的文章中,还将介绍正则表达式。
String命令
String命令实际上是一组操作字符串的命令,它的第一个变元决定了进行什么样子的操作,所有String的命令如下:
命令 | 说明 |
string bytelength str | 返回用于存储字符串的字节数,由于UTF8编码的原因,这个长度可能与string length返回长度不一样 |
string compare ?-nocase? ?-length len? Str1 str2 | 根据词典顺序比较两个字符串,nocase表示忽略大小写,length表示比较前n个字符,如果相同返回值为0,如果str1靠前就返回-1,对于其他情况返回1 |
string equal ? –nocase? Str1 str2 | 比较字符串,如果相同返回1,否则-1,使用nocase来表示忽略大小写 |
string first str1 str2 | 返回str2中str1第一次出现的位置,如果没有的话,就返回-1。 |
string is class ?-strict? ?-failindex varname? string | 如果string属于某个class就返回,如果指定了strict,那么就不匹配空字符串,否则总是要匹配,如果指定了failindex,就会将在string中阻止其称为class一员的字符串索引赋给varname, |
string last str1 str2 | 返回str2中str1最后一次出现的位置,如果没有出现就返回-1 |
string length str | 返回string中的字符个数 |
string map ?-nocase? charMap string | 返回一个根据charmap中输入输出列表将string中的字符进行映射后产生的字符串。 |
string match pattern str | 如果str匹配pattern就返回1,否则返回0, |
string ranger str i j | 返回字符串中从i到j的部分。 |
string repeat str count | 返回将str重复count次的字符串 |
string replace str first last ?newstr? | 返回一个通过把从first到last字符串替换为newstr的新字符串,或是返回空 |
string tolower string ?first? ?last? | 返回string的小写形式,first和last决定了字符串位置 |
string totitle string ?first? ?last? | 将第一个字符替换为大写,其他为小写,first和last决定了字符串位置 |
string toupper string ?first? ?last? | 返回string的大写格式,first和last决定了字符串位置 |
string trim string ?chars? | 从string两端除去chars中指定的字符,chars默认空 |
string trimleft string ?chars? | 从string的左端除去chars中指定的字符,chars默认为空 |
string trimright string ?chars? | 从string的右端除去chars指定的字符,chars默认为空 |
string wordend str ix | 返回str中在索引ix位置包含的字符的单词之后的字符的索引位置 |
string wordstart str ix | 返回str中在索引ix位置包含字符串的单词中第一个字符的索引位置。 |
对于我来说,常用的有如下几个方法,length,equal,match,range,first。请看下面的程序
[ppcorn@localhost ppcorn]$ l
#!/usr/bin/tclsh
set str1 "str1"
set str2 "str1"
set str3 "isstr1?"
set str4 "the index of str1"
# print the length of str1,the value should be 4
puts [string length $str1]
# print the str1 equal str2, the value should be 1
puts [string equal $str1 $str2]
# print the str2 match str3, the value should be 1
puts [string match *$str1* $str3]
# print the 4 to 9 of str4, the value should be index
puts [string range $str4 4 9]
# print the postion of first str1 in str4, the value should be 13
puts [string first $str1 $str4]
[ppcorn@localhost ppcorn]$ ./l
4
1
1
index
13
请注意一下string match的用法,中间使用了*$str1*的用法,这里使用了模糊匹配。一共有三种进行匹配的方式
* | 匹配任意数量字符 |
? | 确切的匹配一个字符 |
[chars] | 匹配chars中的任意一个字符 |
具体用法如
string match ?? XY
string match {[ab]*x} box
string match {[a-zA-Z0-9]} $char
其中$char为任意字符
等等,上述值都为1,表示匹配,有兴趣的朋友可以自己调试。
更多推荐
字符串,字符,位置,匹配,返回,进行,决定
发布评论