我可以使用 totitle 转换 space 的字符串吗?

Can I convert a string with space using totitle?

Tcl 文档清楚地说明了如何使用 string totitle:

Returns a value equal to string except that the first character in string is converted to its Unicode title case variant (or upper case if there is no title case variant) and the rest of the string is converted to lower case.

是否有变通方法或方法可以转换带空格的字符串(每个单词的首字母大写)?

例如 Python:

intro : str = "hello world".title()
print(intro) # Will print Hello World, notice the capital H and W. 

在 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 实际上擅长于此) .

Donal 给了你一个答案,但有一个包可以让你做你想做的事textutil::string from Tcllib

package require textutil::string
puts [::textutil::string::capEachWord "hello world"] 
> Hello World