I just need a function that will, for two given strings, return negative, positive or zero value. In C, strcmp
is used:
char* a = "Hello";
char* b = "Aargh";
strcmp(a, b); //-1
strcmp(a, a); //0
strcmp(b, a); //1
Does Java have any easy intuitive way to do it, or do I have to use the Comparator
interface?
Does Java have any easy intuitive way to do it?
Yes, it does: java.lang.String
implements Comparable<String>
interface, with compareTo
function:
int comparisonResult = a.compareTo(b);
There is also a case-insensitive version:
int comparisonResult = a.compareToIgnoreCase(b);
The String.compareTo method is the way to go in Java.
How to use it :
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is less than str2");
}
else if (retval == 0) {
System.out.println("str1 is equal to str2");
}
else {
System.out.println("str1 is greater than str2");
}
}
}
Output :
str1 is less than str2
Example taken from : http://www.tutorialspoint.com/java/lang/string_compareto.htm
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