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?
The only character operator is the concatenation operator, // . Concatenate a with z . The result of concatenating two strings is a third string that contains the characters of the left operand followed immediately by the characters of the right operand.
The INDEX function returns the starting position of a substring within a string.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With