字符串基本用法
#字符串表示
#字符串本身可以不用单独标识,不含空格时
#字符串使用“”或者{}
#字符串本身带双引号的用 \ 或 {}
set sample "He said,
\" which is a sample comment \" \n "
puts $sample
=>
He said,
" which is a sample comment "
#指定重复次数#string repeat
puts [string repeat $sample 2]
=>
He said,
" which is a sample comment "
He said,
" which is a sample comment "
#指定字符类型 sting is 返回 0/1
#字母、数字
puts [string is alpha $sample]
puts [string is alnum $sample]
=>
0
0
#字符串长度 string length 包括空格
puts [string length $sample]
=>
46
#索引值
#字符定位:索引值
# 字符 H E L L O
# 索引值1 0 1 2 3 4 5
# 索引值2 end-5 end-4 end-3 end-2 end-1 end
#字符索引string index
#end-5 之间不能有空格
puts [string index $sample 1]
puts [string index $sample end-5]
=>
e
d
#字符获取 sring range $c x y
# x < y 返回字符串
# x = y 返回xy对应字符
# x > y 返回空
puts [string range $sample 2 5]
puts [string range $sample 4 4]
=>
sai
a
#字符串添加拼接 append
set str1 hello
set str2 tcl
puts [set str3 $str1$str2]
puts [append str1 $str2 ]
=>
hellotcl
hellotcl
#字符串删除与替换string replace
#三个参数 字符串删除
puts [string replace $str1 0 3]
#四个参数 字符替换
puts [string replace $str1 0 3 $str2 ]
=>
otcl
tclotcl
#字符串比较 string compare x y
# x 先于 y 返回 -1
# x = y 返回 0
# x 后于 y 返回 1
# -nocase 不考虑大小写
# -length i 比较前i个字符
set str1 tck
set str2 tcl
puts [string compare $str1 $str2 ]
puts [string compare -length 2 $str1 $str2 ]
=>
-1
0
#string equal 判断是否相等,相等返回1 否则0
#与compare用法一致
#返回每次执行时间time
puts [ time { string compare $str1 $str2 } 1000 ]
=>
0.2065 microseconds per iteration
#字符串索引
string first 从头索引,返回第一个索引值
string last 从尾索引,返回最后一个索引值
string first th $str 25
string last th $str 35
#字符匹配通配符
string match