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?
string index string charIndex. Returns the charIndex'th character of the string argument. A charIndex of 0 corresponds to the first character of the string. If charIndex is less than 0 or greater than or equal to the length of the string then an empty string is returned.
The string commandUse 'first' or 'last' to look for a substring. The return value is the index of the first character of the substring within the string. The 'string match' command uses the glob-style pattern matching like many UNIX shell commands do. Matches any number of any character.
string range string first last. Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.
A string is a sequence of characters. String in Tcl, unlike in other languages, need not be always enclosed within double quotes. They are necessary only if we have a space between words. Tcl is a string based language. It provides a rich set of commands for manipulating strings.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With