String comparison: Difference between revisions

→‎Tcl: Added implementation
m (tidy up task description)
(→‎Tcl: Added implementation)
Line 35:
80 IF A$ >= B$ THEN PRINT A$;" IS NOT LEXICALLY LOWER THAN ";B$
90 END</lang>
 
=={{header|Tcl}}==
The best way to compare two strings in Tcl for equality is with the <code>eq</code> and <code>ne</code> expression operators:
<lang tcl>if {$a eq $b} {
puts "the strings are equal"
}
if {$a ne $b} {
puts "the strings are not equal"
}</lang>
The numeric <code>==</code> and <code>!=</code> operators also mostly work, but can give somewhat unexpected results when the both the values ''look'' numeric. The <code>string equal</code> command is equally suited to equality-testing (and generates the same bytecode).
 
For ordering, the <code>&lt;</code> and <code>&gt;</code> operators may be used, but again they are principally numeric operators. For guaranteed string ordering, the result of the <code>string compare</code> command should be used instead (which uses the unicode codepoints of the string):
<lang tcl>if {[string compare $a $b] < 0} {
puts "first string lower than second"
}
if {[string compare $a $b] > 0} {
puts "first string higher than second"
}</lang>
Greater-or-equal and less-or-equal operations can be done by changing what exact comparison is used on the result of the <code>string compare</code>.
 
Tcl also can do a prefix-equal (approximately the same as <code>strncmp()</code> in [[C]]) through the use of the <tt>-length</tt> option:
<lang tcl>if {[string equal -length 3 $x "abc123"]} {
puts "first three characters are equal"
}</lang>
And case-insensitive equality is (orthogonally) enabled through the <tt>-nocase</tt> option. These options are supported by both <code>string equal</code> and <code>string compare</code>, but not by the expression operators.
 
=={{header|UNIX Shell}}==
Anonymous user