Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Tags:

java

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.

like image 334
sylvester Avatar asked Mar 01 '11 10:03

sylvester


People also ask

How do you check if a string is less than another string in Java?

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).

How do you compare two strings in alphabetical order?

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.

Which function will be used for finding the smaller string between two strings in alphabetical order?

Compare Strings Alphabetically Using the Traditional Way The compareStrings() is the method where the comparison occurs.


1 Answers

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 
like image 153
Johan Sjöberg Avatar answered Sep 21 '22 18:09

Johan Sjöberg