String.compareTo might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
Answer from Buhb on Stack OverflowString.compareTo might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
Take a look at the String.compareTo method.
Copys1.compareTo(s2)
From the javadocs:
The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
Videos
Hint: All basic data type classes in java implement Comparable interface.
CopyString a="LetterA";
String b="ALetterB";
int compare = a.compareTo(b);
if (compare < 0){
System.out.println(a+" is before "+b);
}
else if (compare > 0) {
System.out.println(b+" is before "+a);
}
else {
System.out.println(b+" is same as "+a);
}
Copyint compare = a.compareTo(b);
if (compare < 0){
System.out.println(a + " is before " +b);
} else if (compare > 0) {
System.out.println(b + " is before " +a);
} else {
System.out.println("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
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.
}