开发者

implement string comparison in android

开发者 https://www.devze.com 2023-04-12 08:20 出处:网络
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:

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. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号