比较多个字符串的android

时间:2019-02-14 00:57:06

标签: java android string-comparison

我想做的是检查多个字符是否为null,以便进行下一个活动,例如:

if( string1.equal(null) && ... stringN.equal(null))
{ Toast.makeText(this, "something is empty", Toast.LENGTH_SHORT).show();}
else
{ GO TO THE NEXT ACTIVITY}

所有字符串都必须有内容...任何帮助都将非常有用

4 个答案:

答案 0 :(得分:0)

如果您的字符串在列表或数组中,则可以对其进行迭代。

如果使用ArrayList:

private boolean verify(final ArrayList<String> list)
{
    for (String entry : list)
    {
        if (TextUtils.isEmpty(entry))
            return false;
    }

    return true;
}

或者,如果使用数组,则只需将参数更改为String []:

private boolean verify(final String[] list)
{
    for (String entry : list)
    {
        if (TextUtils.isEmpty(entry))
            return false;
    }

    return true;
}

答案 1 :(得分:0)

您也可以这样:

private String[] array;

private String one = "one";
private String two = "two";
private String three = "three";
private String four = "four";
private String five = "five";


private void someMethod(){
    if(isStringsNotNull(getStringArray())){
        //Start another activity
    } else {
        //Do something
    }
}

private String[] getStringArray(){
    return new String[]{one, two, three, four, five};
}

private Boolean isStringsNotNull(String[] array){
    for(String str: array){
        if(str == null){
            return false;
        }
    }
    return true;
}

@PerracoLabs的答案很好,但是isEmpty仅检查长度是否为0。不是吗?

答案 2 :(得分:0)

如果您使用的是java8 / lambda,则可以尝试使用以下功能:

List<String> stringList = new ArrayList<>(Arrays.asList(string2.split(" "))); // Split the string into list
        // compare the list with the source of the string, if match put into the list of result
        List<String> result = stringList.stream().filter(new Predicate<String>() {
            @Override
            public boolean test(String s) {
//                return string1.contains(s); // case sensitive
                return Pattern.compile(Pattern.quote(s), Pattern.CASE_INSENSITIVE).matcher(string1).find(); // case insensitive
            }
        }).collect(Collectors.toList());

        // check the match results
        if(result.size()<stringList.size()){
            Log.d("test", "onCreate: not match");
        }else{
            Log.d("test", "onCreate: match");
        }

答案 3 :(得分:0)

如果要检查的字符串数不固定,我将执行以下操作:

private boolean validate(String... items) {
  for (String item : items) {
    if (TextUtils.isEmpty(item)) {
      return false;
    }
  }
  return true;
}

然后您的代码将根据需要验证的字符串数来调用validate方法:

if (validate(string1, string2, stringN)) {
  Toast.makeText(this, "something is empty", Toast.LENGTH_SHORT).show();
} else { 
  // GO TO THE NEXT ACTIVITY
}