Java中的字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4064633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String Comparison in Java
提问by Harshana
What does "compare two strings lexicographically" mean?
“按字典顺序比较两个字符串”是什么意思?
采纳答案by Philip
Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.
根据@Bozho 和@aioobe 的回答,词典比较类似于人们可能在字典中找到的排序。
The Java String class provides the .compareTo ()
method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana")
.
Java String 类提供了.compareTo ()
按字典顺序比较字符串的方法。它是这样使用的"apple".compareTo ("banana")
。
The return of this method is an int
which can be interpreted as follows:
此方法的返回是 an int
,可以解释如下:
- 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.
- 返回 < 0 则调用该方法的字符串按字典顺序排在第一位(在字典中排在第一位)
- 返回 == 0 那么这两个字符串在字典上是等价的
- 返回 > 0 则传递给该
compareTo
方法的参数首先按字典顺序排列。
More specifically, the method provides the first non-zero difference in ASCII values.
更具体地说,该方法提供了 ASCII 值的第一个非零差异。
Thus "computer".compareTo ("comparison")
will return a value of (int) 'u' - (int) 'a'
(20). Since this is a positive result, the parameter ("comparison"
) is lexicographically first.
因此"computer".compareTo ("comparison")
将返回值(int) 'u' - (int) 'a'
(20)。由于这是一个肯定的结果,参数 ( "comparison"
) 按字典顺序排在第一位。
There is also a variant .compareToIgnoreCase ()
which will return 0
for "a".compareToIgnoreCase ("A");
for example.
还有一个变种.compareToIgnoreCase ()
,它将返回0
用于"a".compareToIgnoreCase ("A");
例如。
回答by aioobe
If you check which string would come first in a lexicon, you've done a lexicographical comparison of the strings!
如果您检查哪个字符串将首先出现在词典中,那么您已经完成了字符串的字典序比较!
Some links:
一些链接:
- Wikipedia - String (computer science) Lexicographical ordering
- Note on comparisons: lexicographic comparison between strings
Stolen from the latter link:
从后一个链接中窃取:
A string s precedes a string t in lexicographic order if
- sis a prefix of t, or
- if cand dare respectively the first character of sand tin which sand tdiffer, then cprecedes din character order.
Note: For the characters that are alphabetical letters, the character order coincides with the alphabetical order. Digits precede letters, and uppercase letters precede lowercase ones.
Example:
- house precedes household
- Household precedes house
- composer precedes computer
- H2O precedes HOTEL
字符串 s 在字典顺序中位于字符串 t 之前,如果
- s是t的前缀,或
- 如果c和d分别是s和t中s和t不同的第一个字符,则c按字符顺序排在d之前。
注:对于字母为字母的字符,字符顺序与字母顺序一致。数字在字母之前,大写字母在小写字母之前。
例子:
- 房子先于家庭
- 家先于家
- 作曲家先于计算机
- H2O 先于 HOTEL
回答by Bozho
The String.compareTo(..)
method performs lexicographical comparison. Lexicographically == alphebetically.
该String.compareTo(..)
方法执行词典比较。按字典顺序 == 按字母顺序排列。
回答by Ramp
Comparing sequencially the letters that have the same position against each other.. more like how you order words in a dictionary
按顺序比较具有相同位置的字母彼此……更像是您如何在字典中对单词进行排序
回答by Thorbj?rn Ravn Andersen
The wording "comparison" is mildly misleading. You are not comparing for strict equality but for which string comes first in the dictionary (lexicon).
“比较”这个词有点误导。您不是在比较严格相等,而是比较哪个字符串首先出现在字典(词典)中。
This is the feature that allows collections of strings to be sortable.
这是允许对字符串集合进行排序的功能。
Note that this is verydependent on the active locale. For instance, here in Denmark we have a character "?" which usedto be spelled as "aa" and is very distinct from two single a's (EDIT: If pronounced as"?"!). Hence Danish sorting rules treat two consequtive a's identically to an "?", which means that it goes after z. This also means that Danish dictionaries are sorted differently than English or Swedish ones.
请注意,这非常依赖于活动的语言环境。例如,在丹麦,我们有一个字符“?” 它曾经被拼写为“aa”并且与两个单一的 a 非常不同(编辑:如果发音为“?”!)。因此丹麦的排序规则将两个连续的 a 等同于一个“?”,这意味着它在 z 之后。这也意味着丹麦语词典的排序方式与英语或瑞典语词典不同。
回答by Beezer
Java lexicographically order:
Java字典顺序:
- Numbers -before-
- Uppercase -before-
- Lowercase
- 数字 - 之前 -
- 大写 -before-
- 小写
Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):
这看起来很奇怪,但确实如此……
我必须编写比较器链才能更改默认行为。
使用以下代码片段和更好的输入字符串示例来验证顺序(您将需要 JSE 8):
import java.util.ArrayList;
public class HelloLambda {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Kambiz");
names.add("kambiz");
names.add("k1ambiz");
names.add("1Bmbiza");
names.add("Samantha");
names.add("Jakey");
names.add("Lesley");
names.add("Hayley");
names.add("Benjamin");
names.add("Anthony");
names.stream().
filter(e -> e.contains("a")).
sorted().
forEach(System.out::println);
}
}
Result
结果
1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz
1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz
Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.
请注意,这是特定于语言环境的答案。
请注意,我正在过滤包含小写字母 a 的名称。
回答by Ved Prakash
Below Algo "compare two strings lexicographically"
在 Algo 下面“按字典顺序比较两个字符串”
Input two strings string 1 and string 2.
for (int i = 0; i < str1.length() && i < str2.length(); i ++)
(Loop through each character of both strings comparing them until one of the string terminates):
a. If unicode value of both the characters is same then continue;
b. If unicode value of character of string 1 and unicode value of string 2 is different then return (str1[i]-str2[i])
if length of string 1 is less than string2
return str2[str1.length()]
else
return str1[str2.length()]
// This method compares two strings lexicographically
public static int compareCustom(String s1, String s2) { for (int i = 0; i < s1.length() && i< s2.length(); i++) { if(s1.charAt(i) == s2.charAt(i)){ //System.out.println("Equal"); continue; } else{ return s1.charAt(i) - s2.charAt(i); } } if(s1.length()<s2.length()){ return s2.length() - s1.length(); } else if(s1.length()>s2.length()){ return s1.length()-s2.length(); } else{ return 0; } }
输入两个字符串 string 1 和 string 2。
for (int i = 0; i < str1.length() && i < str2.length(); i ++)
(循环比较两个字符串的每个字符,直到其中一个字符串终止):
一种。如果两个字符的 unicode 值相同,则继续;
湾 如果字符串 1 的字符的 unicode 值和字符串 2 的 unicode 值不同,则返回 (str1[i]-str2[i])
如果字符串 1 的长度小于字符串 2
返回 str2[str1.length()]
别的
返回 str1[str2.length()]
// 此方法按字典顺序比较两个字符串
public static int compareCustom(String s1, String s2) { for (int i = 0; i < s1.length() && i< s2.length(); i++) { if(s1.charAt(i) == s2.charAt(i)){ //System.out.println("Equal"); continue; } else{ return s1.charAt(i) - s2.charAt(i); } } if(s1.length()<s2.length()){ return s2.length() - s1.length(); } else if(s1.length()>s2.length()){ return s1.length()-s2.length(); } else{ return 0; } }
if two String are equal it will return 0 otherwise return Negative or positive value
如果两个 String 相等则返回 0 否则返回负值或正值
Source : - Source
来源: -来源