Search code examples
for-looptcltoupper

How to keep the spaces in a string while doing for loop in tcl


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.


Solution

  • 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)