0

嗨,我有一个字符串,例如{ 这是非常美好的一天!是不是 }。我必须将每个单词的所有第一个字母都改为小写,但空格也应该在那里。为了更改为大写,我使用了以下代码,但我也不知道如何包含空格。代码是:

set wordlist {  Its A Very Good Day! Isn't It  }    
set newlistupper [list]    
for {set i 0} {$i < [llength $wordlist]} {incr i} {
set word [lindex $wordlist $i]
set newupper [string toupper $word 0 0]
lappend newlistupper $newupper
}
puts $newlistupper

我想知道如何在输出中保留空格。请帮忙。

4

2 回答 2

0

您可以使用与我对上一个问题的回答类似的技术:

set sentence {  Its A Very Good Day! Isn't It  }
set lc [subst -nob -nov [regsub -all {\s[[:upper:]]} $sentence {[string tolower "&"]}]]
puts ">$lc<"
>  its a very good day! isn't it  <

另一种方法

% regexp -all -inline -indices {\s[[:upper:]]} $sentence 
{1 2} {5 6} {7 8} {12 13} {17 18} {22 23} {28 29}
% set lc $sentence
  Its A Very Good Day! Isn't It  
% foreach match [regexp -all -inline -indices {\s[[:upper:]]} $sentence ] {
    set lc [string replace $lc {*}$match [string tolower [string range $lc {*}$match]]]
}
% puts ">$lc<"
>  its a very good day! isn't it  <
于 2013-07-30T00:36:36.157 回答
0

我会像这样修改您当前的脚本:

set wordlist {  Its A Very Good Day! Isn't It  }    
set newlistlower [list]    
foreach word [regexp -inline -all -- {\W+|\w+} $wordlist] {
    set newlower [string tolower $word 0 0]
    lappend newlistlower $newlower
}
puts [join $newlistlower ""]

[regexp -inline -all -- {\W+|\w+} $wordlist]将字符串拆分为单词和非单词字符,这意味着您可以保留空格和标点符号等。

foreach允许您获取每个单词(空格也进入循环,但string tolower不会影响它们)。

这也适用于字符串,例如:

set wordlist {Its A Very Good Day! Isn't It--RIGHT  }

给:

{its a very good day! isn't it--rIGHT  }

(大括号表示保留了右侧的尾随空格)

于 2013-07-30T11:33:00.623 回答