implement string comparison in android
I am working on an application that churns output based on comparison of string input. I realize however that most modes of comparison are not applicable to strings. By these I am referring to:
- less than(<)
- less than and equal to(<=)
- greater than(>)
- greater than and equal to(>=)
- equal to(==)
Is there a workaround that anyone might know about? I would appreciate any advice.
Thanks.
[RE-EDIT]
My application is a form that includes various fields. For instance when one enters a value in one textfield, that value is compared against a target value based on the开发者_如何学编程 conditions I listed above. And based on the result, execution can proceed.
I hope this sheds some light.
You can use String.compareTo(String)
that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
What comparison do you need to do? The compareTo() method on String might do the trick.
If you have strings containing nummeric values you should try parsing them to a nummeric representation first. I.e.:
try {
long number1 = Long.parseLong(myString1);
long number2 = Long.parseLong(myString2);
if(number1 <= number2) {
// dosomething
}
} catch(NumberFormatException e) {
Log.e(TAG, "can not parse string to long",e);
}
for simple equals comparision there is the String.equals
method:
if(myString1.equals(myString2)) {
// dosomething
精彩评论