[英]How can I compare two strings in java and define which of them is smaller than the other alphabetically?
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.例如,如果用户的字符串是
abcda
而文件的字符串是abcza
,则很明显用户的字符串小于文件的字符串。 How is it implemented in java?它是如何在java中实现的? it will be great if you can help me with a sample code.
如果您能帮我提供示例代码,那就太好了。
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 ,则将返回
a negative number
,如果相等则返回0
,如果str1更大则返回a positive number
。
Eg,例如,
"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns 0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException
If you would like to ignore case you could use the following:如果您想忽略大小写,您可以使用以下命令:
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.
}
Haven't you heard about the Comparable
interface being implemented by String
?你没听说过
String
实现的Comparable
接口吗? If no, try to use如果没有,请尝试使用
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.它将为您的问题的解决方案输出一个好的根源。
String bigString = null;
for(int i = 0; i < number; i++){
System.out.println("... ");
String sentence = sc.nextLine();
if(bigString == null || sentence.compareTo(bigString) > 0) {
bigString = sentence;
}
}
System.out.println("...: " + bigString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.