比较多个字符串 android

Compare multiple strings android

我想做的是检查多个字符串是否为空,以便转到下一个 activity,像这样:

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

所有字符串都必须有内容...任何帮助都会很棒

如果您的字符串在列表或数组中,那么您可以迭代它们。

如果使用 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;
}

你也可以这样做:

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。不是吗?

如果你使用的是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");
        }

如果您要检查的字符串数量可变,我会执行以下操作:

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

然后您的代码将使用您需要验证的尽可能多的字符串调用验证方法:

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