简体   繁体   中英

check if string array contains value

I have to check, if String Array test2[] contains a value of test1[] . How to do that? Both Arrays have different size. I also have to check if test2[] contains a substring of test1[] .

String[] test = {"Test1", "Test2"};
String[] test2 = {"Test3", "Test4", "Test5", "Test6", "Test1 - Test7"};

Thanks a lot.

You just need couple nested loops and iterate. Your question is ambiguous and the contains word you say might mean equals or contains the substring . In either case, if you want equal match, just replace .contains() with .equals() .

for (String value : test) {
        for (String sampleString : test2) {
            if (sampleString.contains(value)) {
                System.out.println("Value " + value + " is contained in the array in " + sampleString);
            }
        }
    }
public boolean checkIfHaveSameElements(String[] test1, String[] test2) {
    for (String str2 : test2) {
        for (String str1 : test1) {
            if (str2.equals(str1)) {
                return true;
            }
        }
    }
    return false;
}

Just pass your arrays as method call argumnents.

You could use two for loops, one to iterate test and the other to check if the item is contained in test2

public static boolean checkIfExists(String[] arr, String item) {
    for (String n : arr) {

         if (n.contains(item)) {
            return true;
         }
      }
      return false;
   }

And in main method

String[] test = {"Test1", "Test2"};
String[] test2 = {"Test3", "Test4", "Test5", "Test6", "Test1 - Test7"};
for(String t : test) {
    System.out.println(checkIfExists(test2, t));
}

Using Java 8 APIs, I am first checking whether the entire string is present or whether the substring is present.

public class CheckString {

public static void main(String[] args) {      

    String[] test = {"Test1", "Test3", "Test2"};
    String[] test2 = {"Test3", "Test4", "Test5", "Test6", "Test1 - Test7"};

    boolean isPresent = Arrays.stream(test2)
                              .filter(str->{
                               return Arrays.asList(test).indexOf(str) > 0 || checkString(test,str);
                               })
                              .collect(Collectors.toList())
                              .isEmpty();

    System.out.println(!isPresent);

    }
    private static boolean checkString(String[] strs, String chkStr){
        for(String str: strs){
            if(chkStr.contains(str)){
                return true;
            }
        }
        return false;
    }
}

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