【问题标题】:Can I convert a string with space using totitle?我可以使用 totitle 转换带有空格的字符串吗?
【发布时间】:2020-05-07 19:11:36
【问题描述】:

Tcl 文档中明确说明了如何使用string totitle

返回一个等于 string 的值,除了第一个字符 string 被转换为它的 Unicode 标题大小写变体(或大写 如果没有标题大小写变体)并且字符串的其余部分是 转换为小写

是否有一种解决方法或方法可以转换带有空格的字符串(每个单词的第一个字母大写)?

例如在Python:

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

【问题讨论】:

    标签: tcl uppercase


    【解决方案1】:

    在 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 元字符,它会向下; 可以解决这个问题的,但是这样做很糟糕;我在regsub 中添加了-command 选项,正是因为我厌倦了不得不做一个多阶段替换只是为了制作一个我可以通过subst 提供的字符串。这是安全版本(输入阶段也可以使用string map):

    set tcstr [subst [regsub -all {\w+} [regsub -all {[][$\\]} $str {\\&}] {[string totitle &]}]]
    

    当您想要对已转换的子字符串进行实际替换时,它变得非常复杂(嗯,至少相当不明显)。这就是为什么现在可以绕过regsub -command 在执行替换命令运行时注意字边界的所有麻烦(因为 Tcl C API 实际上擅长于此)。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-09-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        相关资源
        最近更新 更多