ratzip
ratzip

Reputation: 113

how to check if the first element of string is a zero in TCL?

I have the following code in TCL:

set num1 "00"
set num2 "02"
set num3 "12"

I want to do is: if the first digit is 0, then only take the second digit. For example:

num1 is "00", then I will set num1 as "0"
num2 is "02", then I will set num1 as "2"
num3 is "12", then it is still "12"

how to check the first digit is zero?

Upvotes: 0

Views: 1243

Answers (3)

Bryan Oakley
Bryan Oakley

Reputation: 385890

You can use string first, which returns the index of the first occurrence of a character. If it returns 0 (zero), the string begins with that character. Note, however, that if you have a really long string this could have performance implications, because if there are no zeros in the string it will examine every character until the end.

if {[string first 0 $num1] == 0} {
    set num1 [string range $num1 1 end]
}

Another choice is to use string match. This is arguably the most readable way to solve the problem, and will run very quickly.

if {[string match {0*} $num1]} {
    set num1 [string range $num1 1 end]
}

Yet another way is to get the first character and compare it to zero. Like using string match, this will run very quickly.

if {[string index $num1 0] == 0} {
    set num1 [string range $num1 1 end]
}

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246764

The scan command is useful here

set num1 "00"
set num2 "02"
set num3 "12"
set num4 "08"   ;# an invalid octal number

foreach val [list $num1 $num2 $num3 $num4] {puts [scan $val %d]}
0
2
12
8

To save the value back to the variable:

foreach var {num1 num2 num3 num4} {
    set $var [scan [set $var] %d]
    puts "$var=[set $var]"
}
num1=0
num2=2
num3=12
num4=8

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

To check if the first character is 0, use string match:

if {[string match "0*" $str]} {
    set rest [string range $str 1 end]
    ...
}

Upvotes: 0

Related Questions