What's the most efficient way of checking whether a string begins with a certain character in TCL?
Asked Answered
G

2

9

I have a string, and I want to check whether it begins with a certain character (# in this case). I'd like to know the most efficient way of doing this!

What I'm thinking of is if {[string compare -length 1 $string "#"]}, because it might use strcmp() which will probably be one of the fastest ways to achieve this.

What I think might also be possible is if {[string index $string 1] == "#"}, because it might do *string == '#' which will probably also be very fast.

What do you think?

Gerlachovka answered 29/7, 2012 at 0:49 Comment(1)
While string compare -length does end up using the equivalent of strncmp(), it has to be more careful than you might imagine because Tcl uses Unicode characters and not ASCII and NUL is a legal character in a Tcl string.Devote
D
22

The fastest method of checking whether a string starts with a specific character is string match:

if {[string match "#*" $string]} { ... }

The code to do the matching sees that there's a star after the first character and then the end of the string, and so stops examining the rest of $string. It also doesn't require any allocation of a result (other than a boolean one, which is a special case since string match is also bytecode-compiled).

Devote answered 29/7, 2012 at 14:51 Comment(3)
While string match was the most intuitive thing I could think of, it's interesting to learn it's also efficient. I would have thought that it would be less performant because it has to parse all sorts of wildcards and stuff. Well, I'm now using string match, thank you!Gerlachovka
@Jerry: The “wildcard at the end” is a special case in the matcher code.Devote
I want to check if the string starts with character * , but whereas * matches everything in the string.Sinistrocular
K
-2

Yes [string match "*" $string_name] this is what worked for me. This is really fast as compared to regexp or any other utility.

Keirakeiser answered 30/10, 2014 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.