Get integer difference between string just like strcmp
Solution 1
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);
Solution 2
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
Solution 3
What about compareTo
?
int value = a.compareTo(b);
Tomáš Zato
It might be easier to hire new management than to get a new community of volunteers. - James jenkins If you play League of Legends, check my repository: http://darker.github.io/auto-client/ I no longer play and I am actively looking for someone to maintain the project. It helped thousands of people, literally.
Updated on June 04, 2022Comments
-
Tomáš Zato about 2 years
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? -
Tomáš Zato about 10 years+1 for mentioning case insensitive option! Thanks a lot!