A-A+
TCL/TK命令详解之字符串处理函数append
命令:append
作用:将文本添加到一个变量的结尾。此命令需要两个或两个以上的参数,第一个参数作为变量,其余参数是要添加到变量中的文本。
例:
(1)
% set msg ""
% foreach i {1 2 3 4 5} {
append msg "$i squared is [expr $i*$i]\n"
}
% set msg
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
(2)
% set msg test
test
% append msg abc 123 "hello"
testabc123hello
(3)
% append str "test"
test
% set str
test
% append str "one" "two"
testonetwo
解析:如果变量不存在,则新建一个空变量,并将后面的字符串依次添加到变量中。
(4)
1)
% set x hello
hello
% set y world
world
% set x "$x$y"
helloworld
2)
% set x hello
hello
% set y world
world
% append x $y
helloworld
解析:以上两个语句是等效的。但是使用append命令比使用方式1)要高效得多,特别是处理长字符串时。使用append可以避免字符串的复制。