简体   繁体   中英

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:

  1. less than(<)
  2. less than and equal to(<=)
  3. greater than(>)
  4. greater than and equal to(>=)
  5. 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. Ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM