简体   繁体   English

在android中实现字符串比较

[英]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(>). 您可以使用String.compareTo(String)返回一个整数,该整数为负数(<),零(=)或正数(>)。

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. String上的compareTo()方法可能会成功。

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: 对于简单的equals比较,可以使用String.equals方法:

if(myString1.equals(myString2)) {
   // dosomething

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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