Tcl文档中很清楚如何使用 string totitle
:
返回一个等于 绳子 除了第一个字 绳子 被转换为Unicode标题大小写变体(如果没有标题大小写变体,则转换为大写)。字符串的其余部分将被转换为小写字母.
有没有一种变通的方法可以转换一个带空格的字符串(每个单词的第一个字母都是大写)?
例如在 Python
:
intro : str = "hello world".title()
print(intro) # Will print Hello World, notice the capital H and W.
Donal给了你一个答案,但是有一个包可以让你做你想要的事情。textutil::string 从 Tcllib
package require textutil::string
puts [::textutil::string::capEachWord "hello world"]
> Hello World
在Tcl 8.7中,最规范的方法是使用 regsub
随着 -command
应用选项 string totitle
到你想改变的子串。
set str "hello world"
# Very simple RE: (greedy) sequence of word characters
set tcstr [regsub -all -command {\w+} $str {string totitle}]
puts $tcstr
在Tcl的早期版本中,你没有这个选项 所以你需要一个两阶段的转换。
set tcstr [subst [regsub -all {\w+} $str {[string totitle &]}]]
这样做的问题是,如果输入的字符串中有某些Tcl元字符,它就会在下面显示出来。是 可以解决这个问题,但做起来太可怕了;我添加了 -command
选择 regsub
正是因为我受够了要做一个多阶段的替代物,只是为了做一个可以穿透的绳子。subst
. 这里是安全版本(输入阶段也可以用 string map
):
set tcstr [subst [regsub -all {\w+} [regsub -all {[][$\\]} $str {\\&}] {[string totitle &]}]]
当你想对已经转化的子串进行替换时,就会变得非常复杂(至少是非常不明显)。这就是为什么现在我们可以通过使用 regsub -command
那就是在做替换命令运行时要注意字的边界(因为Tcl C API其实很擅长这个)。