Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

splitting string

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Please tell me how to split the following string:

"1234.56"

I want to use the decimal as the delimiter and place each digit into its own variable, for example:

a 1
b 2
c 3
d 4
e 5
f 6


I can do this fairly easily using pointer in c/c++. But just having some hard time with tcl.

Thanks,
 
If you want the first digit preceeded by a, the second digit preceeded by b,.. , here is a solution:
Code:
  set num 1234.56
  set letters {a b c d e f}
  set l -1
  set res {}
  foreach n [split $num ""]   {
    if {$n != "."}     {
      lappend res [list [lindex $letters [incr l]] $n]
    }
  }
  puts [join $res \n]
With my bad english, I'll try to explain what this do.

Splitting the digits from 'num' is matter of:
Code:
[split $num ""]
.
The "" indicates that splitting occurs each "" separator, that is: at each char.
The 'l' var with value -1 is the index in the letters list.
Code:
[incr l]
will return 0 the first time it will be evaled, 1 the second time,..
The 'res' var with empty value will contain the result.

Code:
foreach n [split $num ""]
will eval the following body with n valued to "1", then "2", then...
The complex
Code:
lappend res [list [lindex $letters [incr l]] $n]
is not so hard to understand:
Code:
[incr l]
gives the succeeding indexes in the letters list.
Code:
[lindex $letters [incr l]]
gives the succeeding letters in the list.
Code:
[list [lindex $letters [incr l]] $n]
creates a two items list: the selected letter and the current digit.
And
Code:
lappend res [list [lindex $letters [incr l]] $n]
appends the two items list to the result.

During the process the "." is discarded.

Finally, the result is printed prettyfied by
Code:
[join $res \n]
that insert a newline between the two items lists.

Good luck

ulis
 
Another idea: Same basic thing but "modular".
You could do the same thing with a list.

proc varup {str table {lvl "#0"}} {
set x -1
while {$x < [string length $str]} {
incr x
if {[string index $str $x] != &quot;.&quot;} {
uplevel $lvl &quot;set [string index $table $x] [string index $str $x]&quot;
}
}
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top