2

Say I have a string like this:

set str "BAT-CAT, DOG,ELEPHANT ,LION & MOUSE-ANT ,MONKEY, DONKEY"

Now I want to get STRING as follows:

"BAT-CAT,DOG,ELEPHANT,LION&MOUSE-ANT,MONKEY,DONKEY"

I am using trim function to remove white space but it is not working kindly suggest any regsub or procedure for same thank you

user2901871
  • 219
  • 5
  • 6
  • 10

3 Answers3

7

The best way to remove all spaces from a string is to use string map:

set stripped [string map {" " ""} $originalString]
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
2
regsub -all { } $str ""

This will return: BAT-CAT,DOG,ELEPHANT,LION&MOUSE-ANT,MONKEY,DONKEY

Javide
  • 2,477
  • 5
  • 45
  • 61
2

Another solution is this one.

join [list {*}$str] ""

Using the {*} operator, from Tcl parser point of you writing something like:

join [list BAT-CAT, DOG,ELEPHANT ,LION & MOUSE-ANT ,MONKEY, DONKEY] ""

Now, the list command will create a new list where every element is one of its parameters, and the white spaces are used as parameter separators.

Finally, the join command takes a list as its former parameter and a separator as its latter parameter and build a string formed by the list items separated by the separator. In this case, I'm using the empty string as separator, so the resulting string is composed from list items without anything among them.

You can do it also using this simpler syntax

join $str ""
Marco Pallante
  • 3,923
  • 1
  • 21
  • 26