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 ente
Haven't you heard about the Comparable
interface being implemented by String
? If no, try to use
"abcda".compareTo("abcza")
And it will output a good root for a solution to your problem.
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.
}
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.
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
"b".compareTo(null); // throws java.lang.NullPointerException