string compare

Compares two strings character by character.

string compare ?-nocase? ?-length N? A B

Description

Compares A and B one character at a time, by the code point of each character. The first pair that differs gives the order. When one string is a prefix of the other, the shorter one is first. An empty string is before each other string.

The options come before A and B, each at most once, in any order. With exactly two arguments, the words are A and B also when they start with -: string compare -nocase a compares the text -nocase with a.

Arguments

ArgumentTypeDefaultDescription
AstringrequiredThe first string.
BstringrequiredThe second string.

Options

OptionTypeDefaultSummary
-nocaseflagnoneCompares the letters as lowercase.
-lengthintegernoneCompares only the first N characters of each string.

-nocase

Compares the letters as lowercase.

Compares each pair of characters after a change to lowercase, so A and a are equal. It works for each letter with a case in Unicode, such as É and é. With -length, the case rule applies to the first N characters.

% string compare -nocase ABC abc
0

# B (U+0042) is before a (U+0061).
% string compare B a
-1

% string compare -nocase B a
1

# A unique prefix of an option is the option.
% string compare -n A a
0
% string compare -bogus a b
bad option "-bogus": must be -nocase or -length
-errorcode TCL LOOKUP INDEX option

-length N

Compares only the first N characters of each string.

Compares at most the first N characters of A and of B. A string shorter than N compares as a whole. N of 0 gives 0, and a negative N compares the whole strings.

% string compare -length 2 abc abd
0

% string compare -length -1 abc abd
-1

% string compare -nocase -length 2 ABx abY
0
% string compare -length x abc abd
expected integer but got "x"
-errorcode NONE

Returns

-1 when A is before B, 0 when they are equal, and 1 when A is after B.

Examples

% string compare abc abd
-1

% string compare abd abc
1

% string compare a ab
-1

% string compare "" a
-1

Errors

% string compare a
wrong # args: should be "string compare ?-nocase? ?-length int? string1 string2"
-errorcode TCL WRONGARGS

Facts

Capability
None.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also