文章目录
一、字符串
1.字符串的表示
- 只有一个字是,不需要包含双括号
set myVariable hello - 当表示多个字符串,可以使用双引号或大括号
set myVariable “hello world”
set myVariable {hello world}
1.字符串命令
1.compare string1 string2
比较字符string1和string2字典顺序。如果相等返回0,如果string1在string2出现之前返回-1,否则返回1。
#!/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\'.";
}#这里的\'是'字符
2.string1 string2
返回string2中第一次出现string1索引的位置。如果没有找到,返回-1。
#!/usr/bin/tclsh
set s1 "Hello World"
set s2 "o"
puts "First occurrence of $s2 in s1"
puts [string first $s2 $s1] # s1在s2中第一次出现的位置索引
puts "Character at index 0 in s1"
puts [string index $s1 0] # s1在索引值为0处的字符
puts "Last occurrence of $s2 in s1"
puts [string last $s2 $s1] # s1在s2中最后一次出现的位置索引
index string index
返回索引的字符。
last string1 string2
返回索引string1在string2中出现的最后一次。如果没有找到,返回-1。
3.length string
返回字符串的长度。
#!/usr/bin/tclsh
set s1 "Hello World"
puts "Length of string s1"
puts [string length $s1] #返回11
4.match pattern string
返回1,如果该字符串匹配模式。
5.range string index1 index2
返回指定索引范围内的字符串,index1到index2。
7. tolower string
返回小写字符串。
8.toupper string
返回大写字符串。
#!/usr/bin/tclsh
set s1 "Hello World"
puts "Uppercase string of s1"
puts [string toupper $s1]
puts "Lowercase string of s1"
puts [string tolower $s1]
9.trim string ?trimcharacters?
删除字符串两端的trimcharacters。默认trimcharacters是空白。
trimleft string ?trimcharacters?
删除字符串左侧开始的trimcharacters。默认trimcharacters是空白。
trimright string ?trimcharacters?
删除字符串左端trimcharacters。默认trimcharacters是空白。
#!/usr/bin/tclsh
set s1 "Hello World"
set s2 "World"
puts "Trim right $s2 in $s1"
puts [string trimright $s1 $s2] #删除s1字符串右端的s2
set s2 "Hello"
puts "Trim left $s2 in $s1"
puts [string trimleft $s1 $s2] 删除s1字符串左端的s2
set s1 " Hello World "
set s2 " "
puts "Trim characters s1 on both sides of s2"
puts [string trim $s1 $s2]
2.append命令
添加字符串
#!/usr/bin/tclsh
set s1 "Hello"
append s1 " World"
puts $s1 #返回Hello World
3.format命令
#!/usr/bin/tclsh
puts [format "%f" 13.6]
puts [format "%e" 13.6]
puts [format "%d %s" 2 tuts]
puts [format "%s" "Tcl Language"]
puts [format "%x" 40]
scan命令
分析基于对格式说明的字符串