Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 513
Jerry Avatar asked Jul 29 '12 00:07

Jerry


People also ask

How do I find the first character of a string in Tcl?

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.

How do you check if a string contains a substring Tcl?

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.

What is string first in Tcl?

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.

What is a string in Tcl?

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.


1 Answers

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).

like image 60
Donal Fellows Avatar answered Oct 12 '22 14:10

Donal Fellows