Tcl 的原始數(shù)據(jù)類型是字符串,我們常??梢栽赥cl找到引用字符串的唯一語(yǔ)言。這些字符串可以包含字母數(shù)字字符,數(shù)字,布爾值,甚至是二進(jìn)制數(shù)據(jù)。 TCL采用16位Unicode字符和字母數(shù)字字符,可以包含字母包括非拉丁字符,數(shù)字或標(biāo)點(diǎn)符號(hào)。
布爾值,可以表示為1,yes 或 true 為真值和0,no 或 false 為假值。
不同于其他語(yǔ)言,在TCL,只有一個(gè)字時(shí),不需要包含雙引號(hào)。示例如下,
#!/usr/bin/tclsh set myVariable hello puts $myVariable
當(dāng)上述代碼被執(zhí)行時(shí),它會(huì)產(chǎn)生以下結(jié)果。
hello
當(dāng)要表示多個(gè)字符串,我們可以使用雙引號(hào)或大括號(hào)。它如下所示。
#!/usr/bin/tclsh set myVariable "hello world" puts $myVariable set myVariable {hello world} puts $myVariable
當(dāng)上述代碼被執(zhí)行時(shí),它會(huì)產(chǎn)生以下結(jié)果。
hello world
hello world
字符文字可以是一個(gè)普通的字符(例如,'x'),轉(zhuǎn)義序列(如“\t'),或通用字符(例如,'\u02C0')。
Tcl有一些字符,當(dāng)他們前面加一個(gè)反斜杠他們將有特殊的含義,它們被用來(lái)表示類似的換行符(\n)或制表符(\t)。在這里,有一些轉(zhuǎn)義序列代碼的列表:
轉(zhuǎn)義序列 | 意思 |
---|---|
\\ | \ 字符 |
\' | ' 字符 |
\" | " 字符 |
\? | ? 字符 |
\a | 警報(bào)或鈴 |
\b | 退格 |
\f | 換頁(yè) |
\n | 新一行 |
\r | 回車 |
\t | 水平制表 |
\v | 垂直制表 |
以下為例子來(lái)說(shuō)明一些轉(zhuǎn)義字符序列:
#!/usr/bin/tclsh puts("Hello\tWorld\n\n");
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
Hello World
子命令字符串命令列表列如下表。
SN | 方法及描述 |
---|---|
1 |
compare string1 string2 比較字string1和string2字典順序。如果相等返回0,如果string1在string2出現(xiàn)之前返回-1,否則返回1。 |
2 |
返回string1中第一次出現(xiàn)string1索引的位置。如果沒有找到,返回-1。 |
3 |
index string index 返回索引的字符。 |
4 |
last string1 string2 返回索引string1在string2中出現(xiàn)的最后一次。如果沒有找到,返回-1。 |
5 |
length string 返回字符串的長(zhǎng)度。 |
6 |
match pattern string 返回1,如果該字符串匹配模式。 |
7 |
range string index1 index2 返回指定索引范圍內(nèi)的字符串,index1到index2。 |
8 |
tolower string 返回小寫字符串。 |
9 |
toupper string 返回大寫字符串。 |
10 |
trim string ?trimcharacters? 刪除字符串兩端的trimcharacters。默認(rèn)trimcharacters是空白。 |
11 |
trimleft string ?trimcharacters? 刪除字符串左側(cè)開始的trimcharacters。默認(rèn)trimcharacters是空白。 |
12 |
trimright string ?trimcharacters? 刪除字符串左端trimcharacters。默認(rèn)trimcharacters是空白。 |
13 |
wordend findstring index 返回索引字符findstring包含字符索引單詞。 |
14 |
wordstart findstring index 返回findstring中第一個(gè)字符的含有索引中的字符索引的單詞。 |
一些常用的Tcl字符串子命令的例子在下面給出。
#!/usr/bin/tclsh set s1 "Hello" set s2 "World" set s3 "World" puts [string compare s1 s2] if {[string compare s2 s3] == 0} { puts "String \'s1\' and \'s2\' are same."; } if {[string compare s1 s2] == -1} { puts "String \'s1\' comes before \'s2\'."; } if {[string compare s2 s1] == 1} { puts "String \'s2\' comes before \'s1\'."; }
讓我們編譯和運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
-1 String 's1' comes before 's2'. String 's2' comes before 's1'.
#!/usr/bin/tclsh set s1 "Hello World" set s2 "o" puts "First occurrence of $s2 in s1" puts [string first $s2 $s1] puts "Character at index 0 in s1" puts [string index $s1 0上一篇:TCL continue語(yǔ)句下一篇:TCL變量