我如何比较java中的两个字符串,并定义哪个字符串比另一个字符串更小?

时间:2022-05-01 07:29:56

I want to use the binary search algorithm to search the string which has been entered by the user in a very big sorted file. I can not compare the string which has been entered by the user with the string which has been located in the middle line of the file to continue my binary search.

我想用二进制搜索算法来搜索用户输入的字符串在一个很大的排序文件中。我无法将用户输入的字符串与文件中线的字符串进行比较,以继续我的二进制搜索。

For example, if the user's string is abcda and the file's string is abcza, it is obvious that the user's string is smaller than the file's string. How is it implemented in java? it will be great if you can help me with a sample code.

例如,如果用户的字符串是abcda,而文件的字符串是abcza,那么很明显,用户的字符串小于文件的字符串。它是如何在java中实现的?如果您能帮助我编写一个示例代码就太好了。

3 个解决方案

#1


92  

You can use

您可以使用

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

如果str1在字典上小于str2,则返回一个负数,如果等于0,则返回一个正数,如果str1大于0。

E.g.,

例如,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1

#2


5  

If you would like to ignore case you could use the following:

如果您想忽略case,您可以使用以下方法:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

#3


3  

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

你没听说过用String实现的类似接口吗?如果没有,试着使用

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

它将输出一个好的根来解决您的问题。

#1


92  

You can use

您可以使用

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

如果str1在字典上小于str2,则返回一个负数,如果等于0,则返回一个正数,如果str1大于0。

E.g.,

例如,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1

#2


5  

If you would like to ignore case you could use the following:

如果您想忽略case,您可以使用以下方法:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

#3


3  

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

你没听说过用String实现的类似接口吗?如果没有,试着使用

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

它将输出一个好的根来解决您的问题。