質問

HI I have a string like { Its A Very Good Day! Isn't It }. I have to change all the first letter of every word to lower case but the spaces should also be there. For changing to upper case I have used the following code but I do not know how to include the spaces as well. The code is:

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

I want to know how to keep the spaces also in the output. Please help.

役に立ちましたか?

解決

I would modify your current script a little bit like so:

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] splits the string into word and non-word characters, which means you get to keep spaces and punctuations and so on.

foreach allows you to get each word (spaces get into the loop as well, but string tolower won't be affecting them).

This will also work on strings such as:

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

to give:

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

(Braces put to show that the trailing space on the right is kept)

他のヒント

You can use a similar technique to my answer for your previous question:

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  <

Another way to do 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  <
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top