How can I compare two strings in java and determine which one is smaller than the other in alphabetical order?

I want to use a binary search algorithm to search for a string entered by a user in a very large sorted file. I cannot compare the string entered by the user with the string that was located in the middle line of the file to continue my binary search.

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

+57
java
Mar 01 2018-11-11T00:
source share
3 answers

You can use

 str1.compareTo(str2); 

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

For example,

 "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 
+106
Mar 01 2018-11-11T00:
source share

If you want to ignore the case, you can 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. } 
+6
Jul 03 '13 at 12:51 on
source share

Have you not heard of the Comparable interface that String implements? If not, try using

 "abcda".compareTo("abcza") 

And he will give a good root to solve your problem.

+3
Mar 01 2018-11-11T00:
source share



All Articles