stringfortranstring-comparisonfortran77

Comparing two strings in Fortran


What is the correct way to compare two strings say abc and bcd depending on the alphabetic order? Is there a built in command to do so? Or would > or .lt. do the work without any problems?


Solution

  • The intrinsic relational operators .lt. and < (along with the "equal" and "greater than" friends) indeed may be used to compare character variables.

    We see the definition (Fortran 2018, 10.1.5.5.1):

    the character operand x1 is considered to be less than x2 if the character value of x1 at this position precedes the value of x2 in the collating sequence

    where the comparison is done with the first character part in the corresponding strings which differ.

    The collating sequence tells you whether, for example, 'a' precedes 'b'. So, if 'abc' is compared with 'bcd' then the comparison is between 'a' and 'b'.

    If the two strings to be compared are of different lengths, then the comparison is performed as though the shorter string is padded with blanks (spaces) on the right to make it the same length of the longer. This means that when comparing 'ab' and 'abc' we look at 'ab ' and 'abc': 'ab'<'abc' if and only if ' '<'c'.