2.11.5 String Comparison

D overloads the binary relational operators and permits them to be used for string comparisons, as well as integer comparisons. The relational operators perform string comparison whenever both operands are of type string or when one operand is of type string and the other operand can be promoted to type string. See Section 2.11.3, “String Assignment” for a detailed description. See also Table 2.14, “D Relational Operators for Strings”, which lists the relational operators that can be used to compare strings.

Table 2.14 D Relational Operators for Strings

Operator

Description

<

Left-hand operand is less than right-operand.

<=

Left-hand operand is less than or equal to right-hand operand.

>

Left-hand operand is greater than right-hand operand.

>=

Left-hand operand is greater than or equal to right-hand operand.

==

Left-hand operand is equal to right-hand operand.

!=

Left-hand operand is not equal to right-hand operand.


As with integers, each operator evaluates to a value of type int, which is equal to one if the condition is true or zero if it is false.

The relational operators compare the two input strings byte-by-byte, similarly to the C library routine strcmp(). Each byte is compared by using its corresponding integer value in the ASCII character set until a null byte is read or the maximum string length is reached. See the ascii(7) manual page for more information. Some example D string comparisons and their results are shown in the following table.

D string comparison

Result

"coffee" < "espresso"

Returns 1 (true)

"coffee" == "coffee"

Returns 1 (true)

"coffee"" >= "mocha"

Returns 0 (false)

Note

Seemingly identical Unicode strings might compare as being different if one or the other of the strings is not normalized.