Java中的字符串比较 [英] String Comparison in Java
问题描述
按字典顺序比较两个字符串是什么意思?
What does "compare two strings lexicographically" mean?
推荐答案
来自@Bozho和@aioobe的答案,词典比较类似于字典中可能找到的排序。
Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.
Java String类提供 .compareTo()
方法以字典顺序比较字符串。它像这样使用apple.compareTo(banana)
。
The Java String class provides the .compareTo ()
method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana")
.
此方法的返回是一个 int
,可以解释如下:
The return of this method is an int
which can be interpreted as follows:
- 返回< 0然后调用方法的String首先按字典顺序排在第一位(在字典中排在第一位)
- 返回== 0然后两个字符串按字典顺序相同
- 返回> 0然后传递给
compareTo
方法的参数首先按字典顺序排列。
- returns < 0 then the String calling the method is lexicographically first (comes first in a dictionary)
- returns == 0 then the two strings are lexicographically equivalent
- returns > 0 then the parameter passed to the
compareTo
method is lexicographically first.
更具体地说,该方法提供了ASCII值的第一个非零差异。
More specifically, the method provides the first non-zero difference in ASCII values.
因此computer.compareTo(comparison)
将返回值(int)'u' - (int)'a'
(21)。由于这是一个积极的结果,参数(比较
)首先按字典顺序排列。
Thus "computer".compareTo ("comparison")
will return a value of (int) 'u' - (int) 'a'
(21). Since this is a positive result, the parameter ("comparison"
) is lexicographically first.
还有一个variant .compareToIgnoreCase()
将返回 0
a.compareToIgnoreCase(A );
例如。
There is also a variant .compareToIgnoreCase ()
which will return 0
for "a".compareToIgnoreCase ("A");
for example.
这篇关于Java中的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!