COMPARE()

Top  Previous  Next

 

The COMPARE() function compares two strings using the same rules as the LOCATE statement and the SORT verb.

 

 

Format

 

COMPARE(string1, string2 {, justification})

 

where

 

string1, string2evaluate to the strings to be compared.

 

justificationevaluates to a string where the first character is "L" for left justified comparison or "R" for right justified comparison. If omitted or invalid, left justification is used.

 

 

The COMPARE() function compares the two strings and returns

1string1 is greater than string2
0string1 is equal to string2
-1string1 is less than string2

 

For a left justified comparison, characters are compared one by one and the function return value is determined by the relative ASCII character set positions of the characters at which the first mismatch occurs. If the strings are of different lengths and match up to the end of the shorter, the longer string is treated as the greater.

 

For a right justified comparison, the COMPARE() function behaves as though sufficient spaces were inserted at the start of the shorter string to match the length of the longer string. Characters are then compared one by one and the function return value is determined by the relative ASCII character set positions of the characters at which the first mismatch occurs.

 

The COMPARE() function is not affected by the setting of the  $NOCASE.STRINGS compiler directive and can therefore be used to force a case sensitive comparison in otherwise case insensitive programs..

 

 

Examples

 

A = 0

B = '00'

DISPLAY A = B

DISPLAY COMPARE(A,B)

 

In the above example, use of the relational equals operator will see A and B as equal because both items can be treated as numbers. B is converted to a number (0) and a numeric comparison is performed. Use of the COMPARE() function always treats the items as character strings. A is converted to a string and the two items are compared as left aligned strings, reporting that they are unequal.

 

 

DIM ITEM(100)

ITEMS = 0

LOOP

  INPUT NEW.ITEM

WHILE LEN(NEW.ITEM)

  * Find position to insert new item

  I = 1

  LOOP

  WHILE I <= ITEMS

     IF COMPARE(NEW.ITEM, ITEM(I)) < 0 THEN EXIT

     I += 1

  REPEAT

 

  * Insert item at position I

  FOR J = ITEMS TO I STEP - 1

     ITEM(J + 1) = ITEM(J)

  NEXT J

  ITEM(I) = NEW.ITEM

  ITEMS += 1

REPEAT

 

This program fragment creates a matrix, ITEMS, and then enters a loop to read NEW.ITEM values from the keyboard until a blank line is entered. Each item read is inserted into the matrix in its correct position to maintain the matrix in ascending collating sequence order. Additional statements to detect and handle matrix overflow would be useful in a full application.