這裏對string命令中的幾個子命令使用實例進行一些解釋,以便於更加容易理解string命令中的各個子命令,本文僅對幾個比較容易掌握的相對簡單的string命令進行實例解析。分別是bytelength、length、compare、equal、range、index、first和last幾個子命令。
如果對這些命令還不瞭解,請參考:
string bytelength string
string length string
兩個命令都是返回字符串string的長度。
把以上的兩個命令放在一起比較,更能夠顯現出兩個命令的區別。
bytelength是計算一個字符串的字節數,而length是計算一個字符串的長度,如果字符串爲標準的ASCII碼組成,那麼兩個命令得到的結果是相同的。例如:
% string bytelength "This is a tcltk example"
23
% string length "This is a tcltk example"
23
兩者在有其它字符出現的時候就會有區別了,比如中文:
% string bytelength "這是一個tcltk示例"
23
% string length "這是一個tcltk示例"
11
一箇中文爲三個字節,所以造成了以上兩者的區別,在使用這兩個命令的時候需要注意這個不同點。
string compare ?-nocase? ?-length int? string1 string2
命令返回兩個字符串比較的結果,string1的順序比string2靠前就返回1,反之返回-1,相等返回0。
-nocase的意思就是不區分大小寫,本文下同,不再累述。
-length int中的int就是需要比較的前面幾個字符,本文下同,不再累述。
以下的例子比較兩個字符串:
% string compare "This is a TCLTK example" "This is a tcltk example"
-1
因爲ASCII碼T在t之後,所以從順序上來說後面的字符串顯然在前,所以返回-1,如果把兩個字符串的位置互換:
% string compare "This is a tcltk example" "This is a TCLTK example"
1
如果兩個字符串相同則返回0:
% string compare "This is a tcltk example" "This is a tcltk example"
0
使用-nocase的話就不區分大小寫,第一個例子:
% string compare -nocase "This is a TCLTK example" "This is a tcltk example"
0
因爲不區分大小寫,所以兩個字符串對比結果相等。
只比較字符串的前7個字符"This is",再來使用第一個例子:
% string compare -length 7 "This is a TCLTK example" "This is a tcltk example"
0
因爲前面的7個字符是相同的,所以返回0。
string equal ?-nocase? ?-length int? string1 string2
這個命令比較兩個字符串是否相同。相同返回1,不同返回0。
以下的例子比較兩個不同字符串:
% string equal "This is a TCLTK example" "This is a tcltk example"
-1
比較兩個相同的字符串:
% string equal "This is a tcltk example" "This is a tcltk example"
0
-nocase與-length int的使用方法不再詳述。
string index string charIndex
此命令的使用是string命令當中使用頻率非常高的,而且也非常簡單,就是取出字符串中索引爲charIndex的字符。
舉例如下:
% string index "This is a tcltk example" 14
k
string range string first last
命令取出字符串中索引範圍爲first到last的字符(包括first和last,下同)。
% string range "This is a tcltk example" 1 14
his is a tcltk
his is a tcltk
string first needleString haystackString ?startIndex?
搜尋在haystackString字符串中與needleString字符串完全匹配的字符段,如果找到了返回第一次匹配在haystackString字符串中的索引,如果找不到則返回-1。如果指定了startIndex則在haystackString中從索引startIndex開始搜索。例如:
% string first "tcltk" "This is a tcltk example"
10
10
返回的結果爲字符串tcltk在字符串中第一次出現的子字符串第一個字符的索引。
指定startIndex表示從這個索引開始搜索:
% string first "is" "This is a tcltk example" 4
5
5
如果不指定索引4,則會搜索到This中的is
% string first "is" "This is a tcltk example"
2
2
string last needleString haystackString ?lastIndex?
與first命令相似,只是返回的是最後搜索到的匹配的字符段,lastIndex含義也有所不同,first命令中的index指定了從index往後搜索,而這裏是從index往前,例如:
% string last "is" "This is a tcltk example"
5
5
返回的is不是This中的is,可以指定lastIndex來表示從哪個索引開始搜索:
% string last "is" "This is a tcltk example" 3
2
2
搜索到了This中的is