鍍金池/ 教程/ 物聯(lián)網(wǎng)/ TCL字符串
TCL內(nèi)置函數(shù)
TCL變量
TCL嵌套循環(huán)
TCL決策
TCL循環(huán)
Tcl if...else語句
Tcl教程
TCL字符串
TCL邏輯運算符
TCL Switch語句
TCL列表
TCL運算符優(yōu)先級
TCL數(shù)據(jù)類型
TCL環(huán)境設置
TCL正則表達式
TCL命名空間
TCL運算符
TCL特殊變量
TCL數(shù)組
TCL算術運算符
Tcl For循環(huán)
TCL文件I/O
TCL關系運算符
TCL if語句
TCL命令
TCL基本語法
TCL三元運算符
TCL continue語句
TCL嵌套if語句
TCL字典
TCL break語句
TCL包
TCL 嵌套switch語句
TCL while循環(huán)
TCL位運算符
TCL過程
TCL錯誤處理

TCL字符串

Tcl 的原始數(shù)據(jù)類型是字符串,我們常??梢栽赥cl找到引用字符串的唯一語言。這些字符串可以包含字母數(shù)字字符,數(shù)字,布爾值,甚至是二進制數(shù)據(jù)。 TCL采用16位Unicode字符和字母數(shù)字字符,可以包含字母包括非拉丁字符,數(shù)字或標點符號。

布爾值,可以表示為1,yes 或 true 為真值和0,no 或 false 為假值。

字符串表示

不同于其他語言,在TCL,只有一個字時,不需要包含雙引號。示例如下,

#!/usr/bin/tclsh

set myVariable hello
puts $myVariable

當上述代碼被執(zhí)行時,它會產(chǎn)生以下結果。

hello

當要表示多個字符串,我們可以使用雙引號或大括號。它如下所示。

#!/usr/bin/tclsh

set myVariable "hello world"
puts $myVariable
set myVariable {hello world}
puts $myVariable

當上述代碼被執(zhí)行時,它會產(chǎn)生以下結果。

hello world
hello world

字符串轉(zhuǎn)義序列

字符文字可以是一個普通的字符(例如,'x'),轉(zhuǎn)義序列(如“\t'),或通用字符(例如,'\u02C0')。

Tcl有一些字符,當他們前面加一個反斜杠他們將有特殊的含義,它們被用來表示類似的換行符(\n)或制表符(\t)。在這里,有一些轉(zhuǎn)義序列代碼的列表:

轉(zhuǎn)義序列 意思
\\ \ 字符
\' ' 字符
\" " 字符
\? ? 字符
\a 警報或鈴
\b 退格
\f 換頁
\n 新一行
\r 回車
\t 水平制表
\v 垂直制表

以下為例子來說明一些轉(zhuǎn)義字符序列:

#!/usr/bin/tclsh

puts("Hello\tWorld\n\n");

讓我們編譯和運行上面的程序,這將產(chǎn)生以下結果:

Hello   World

字符串命令

子命令字符串命令列表列如下表。

SN 方法及描述
1

compare string1 string2

比較字string1和string2字典順序。如果相等返回0,如果string1在string2出現(xiàn)之前返回-1,否則返回1。

2

string1 string2

返回string1中第一次出現(xiàn)string1索引的位置。如果沒有找到,返回-1。

3

index string index

返回索引的字符。

4

last string1 string2

返回索引string1在string2中出現(xiàn)的最后一次。如果沒有找到,返回-1。

5

length string

返回字符串的長度。

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。默認trimcharacters是空白。

11

trimleft string ?trimcharacters?

刪除字符串左側(cè)開始的trimcharacters。默認trimcharacters是空白。

12

trimright string ?trimcharacters?

刪除字符串左端trimcharacters。默認trimcharacters是空白。

13

wordend findstring index

返回索引字符findstring包含字符索引單詞。

14

wordstart findstring index

返回findstring中第一個字符的含有索引中的字符索引的單詞。

一些常用的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\'.";
}

讓我們編譯和運行上面的程序,這將產(chǎn)生以下結果:

-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語句下一篇:TCL變量