Reputation: 157
I want to compare the first letter of a string with a known character. For example, I want to check if the string "example"'s first letter matches with "e" or not. I'm sure there must be a very simple way to do it, but I could not find it.
Upvotes: 1
Views: 8947
Reputation: 13252
I think it's a good idea to collect the different methods in a single answer.
Assume
set mystring example
set mychar e
The goal is to test whether the first character in $mystring
is equal to $mychar
.
My suggestion was (slightly edited):
if {[string match $mychar* $mystring]} {
...
This invocation does a glob-style match, comparing $mystring
to the character $mychar
followed by a sequence of zero or more arbitrary characters. Due to shortcuts in the algorithm, the comparison stops after the first character and is quite efficient.
Donal Fellows:
if {[string index $mystring 0] eq $mychar} {
...
This invocation specifically compares a string consisting of the first character in $mystring
with the string $mychar
. It uses the efficient eq
operator rather than the ==
operator, which is the only one available in older versions of Tcl.
Another way to construct a string consisting of the first character in $mystring
is by invoking string range $mystring 0 0
.
Mark Kadlec:
if {[string first $mychar $mystring] == 0 }
...
This invocation searches the string $mystring
for the first occurrence of the character $mychar
. If it finds any, it returns with the index where the character was found. This index number is then compared to 0
. If they are equal the first character of $mystring
was $mychar
.
This solution is rather inefficient in the worst case, where $mystring
is long and $mychar
does not occur in it. The command will then examine the whole string even though only the first character is of interest.
One more string
-based solution:
if {[string compare -length 1 $mychar $mystring] == 0} {
...
This invocation compares the first n characters of both strings (n being hardcoded to 1 here): if there is a difference the command will return -1 or 1 (depending on alphabetical order), and if they are equal 0 will be returned.
Another solution is to use a regular expression match:
if {[regexp -- ^$mychar.* $mystring]} {
...
This solution is similar to the string match
solution above, but uses regular expression syntax rather than glob syntax. Don't forget the ^
anchor, otherwise the invocation will return true if $mychar
occurs anywhere in $mystring
.
Documentation: eq and ==, regexp, string
Upvotes: 2
Reputation: 1
set mychar "e"
if { [string first $mychar $myString] == 0}{
....
Upvotes: -1
Reputation: 137567
One way is to get the first character with string index
:
if {[string index $yourstring 0] eq "e"} {
...
Upvotes: 5