简体   繁体   中英

Find out if a String contain a value in an array in Java

Is there a shorter way to find out if your string contains any of the value in a String[]?

This is my code:

String s = "Hello world! My name is Bao.";
String[] arr = new String[]{"o", "!", "-", "y", "z"};
for (String item : arr) {
    if (s.contains(item)) {
        System.out.println("String s contains: " + item);
    } else {
        System.out.println("String s doesn't contains: " + item);
    }
}

Is there a shorter way of doing this? I don't want to use for loop for this.

It may be slow when the array contains 4000+ strings.

For large arrays of Strings, it will be faster first convert your array and target string to a HashSet . Being a Set will remove duplicate characters, and being Hash ed will make comparison very fast. Then you can do a couple of quick set subtractions to get your answer:

String s = "Hello world! My name is Bao.";
String[] arr = new String[] { "o", "!", "-", "y", "z" };

Set<String> sSet = new HashSet<String>(Arrays.asList(s.split("(?!^)")));
Set<String> arrSet = new HashSet<String>(Arrays.asList(arr));

Collection<String> notFound = CollectionUtils.subtract(arrSet, sSet);
Collection<String> found = CollectionUtils.subtract(arrSet, notFound);

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