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.
Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).
If you are truly comparing Strings alphabetically to arrange them in order, use compareTo() method from Comparable interface in Java. It also compare String based upon there value, and can be used to sort String alphabetically, if they are stored in List using Collections. sort() method.
Compare Strings Alphabetically Using the Traditional Way The compareStrings() is the method where the comparison occurs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With