COMPARE Function

Compares two strings and returns a numeric value indicating the result.

Syntax

COMPARE(string1,string2{,alignment})

Syntax Elements

string1, string2 The string expressions to be compared.

alignment Optional. Specifies whether the strings are to be compared as if left- or right-aligned (see Operation). If specified, must evaluate to "L" (left) or "R" (right). If not specified, the default is left-aligned. If the specified value is neither "L" nor "R", a run time error occurs.

Return Value

The COMPARE function returns the following values:

-1 string1 < string2

0 string1 = string2

1 string1 > string2

Operation

The strings are compared as follows:

  1. If right alignment is specified and and the strings are of different lengths, the longer string is considered the greater.
  2. Otherwise, the comparison proceeds character by character from left to right. Characters are compared by ASCII value (see Decimal, Hexadecimal, and ASCII Table).
  3. With left alignment specified, if the strings are of different length and each character in the shorter string matches the character at the same position in the other, the longer string is considered the greater.

Examples

A=”XYZ11”
B=”XYZ100”
PRINT COMPARE(A,B,'L')
PRINT COMPARE(A,B,'R')

In this case, the first PRINT statement displays 1, because the ASCII code of the final character in A ('1' – 49) is greater than that of the corresponding character in B ('0' – 48). The second PRINT statement, however, displays -1, because right-alignment is selected and string A is longer than string B.

A=”XYZ101”
B=”XYZ100”
PRINT COMPARE(A,B,'L')
PRINT COMPARE(A,B,'R')

In this case, both strings are the same length and both PRINT statements display 1 because the ASCII code of the final character in A ('1' – 49) is greater than that of the corresponding character in B ('0' – 48).

A=”XYZ10”
B=”XYZ100”
PRINT COMPARE(A,B,'L')
PRINT COMPARE(A,B,'R')

In the final example, both PRINT statements display -1 (B > A). In the first case (with left alignment selected), all the characters in A match the corresponding ones in B, but B is longer. In the second case, B is simply longer than A and, because right alignment is selected, no character comparisons are performed.

Go to top button