In any of the programs, string comparison is critical for many reasons. To perform string comparison, Tcl provides two keywords for use with the string
command—compare
and equal
. The syntax for the first keyword compare
is as follows:
string compare -nocase -length string1 string2
When invoked with the compare
keyword, the string
command performs a character-by-character comparison of the strings passed in string1
and string2
.
The string
command accepts two switches as mentioned here:
-nocase
Strings are compared in a case-insensitive manner
-length
Instructs the interpreter to perform the comparison only on the first length characters
To complete the following example, we will need to create a Tcl script file in your working directory. Open the text editor of your choice and follow the given instructions.
In the following example, we will create a Tcl script to accept a string value to compare against a static value. In this method, you can see the specific returns by altering the second string. Using the editor of your choice create a text file named compare.tcl
that contains the following commands:
set string1 compare set string2 [lindex $argv 0] set output [string compare $string1 $string2] puts $output
After you have created the file, invoke the script with the following command line:
% tclsh85 compare.tcl compare
0
As it can be seen, where the return value is 0, the strings are compared and match. Try invoking this script with different arguments to see the other return values. When invoked with the compare
keyword, it will perform a character-by-character comparison of the two strings provided. The return values are -1, 0
, or 1
. These indicate if the string being compared to is lexicographically less than, equal to, or greater than the comparison string. As such, the string
command will return more information on a comparison than the simple ==
method.
3.15.144.56