Comparing two strings in Fortran
Asked Answered
W

1

11

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?

Watkins answered 28/1, 2019 at 5:34 Comment(0)
M
8

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'.

Mcmanus answered 28/1, 2019 at 7:52 Comment(3)
I see, what about the comparison of abc and ab ?Watkins
There is the idea of caps, etc. I.e. Is "fred" intended to be the same as "Frederick"?Krimmer
@Krimmer Caps is considered, lower case is "greater than" upper case, eg. 'a' > 'A'.Saraisaraiya

© 2022 - 2024 — McMap. All rights reserved.