-
String comparison
Hi friends,
i have a doubt about string comparison.
when we use the method like..
Code:
result=st1.compareTo(st2);
then...
result>0 if st1>st2
result=0 if st1=st2
result<0 if st1<st2
how can we compare strings like numbers ?
how this method works ?
what is the use of string comparison ?
please tell me.....
thankq ...
-
You can use the compareTo method for class instances/objects that implement the Comparable interface, egs, String and Integer.
Code:
String s1 = "hello world";
String s2 = "goodbye";
int retVal = s1.compareTo(s2);
boolean equal = s1.equals(s2);
String s3 = "95";
String s4 = "101";
// Which number is larger?
Integer i3 = Integer.valueOf(s3);
int n4 = Integer.parseInt(s4);
Integer i4 = Integer.valueOf(n4);
int compare = i3.compareTo(i4);
System.out.println("compare = " + compare);
System.out.printf("i3 is %s i4%n",
(compare < 1) ? "less than" :
(compare > 1) ? "greater than" : "equal to");
int n3 = i3.intValue();
System.out.printf("n3 < n4 = %b%n", n3 < n4);