Comparing two strings in Fortran

风格不统一 提交于 2020-01-21 12:13:22

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/54396058/comparing-two-strings-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!