Check for Substring in an Array - Java, Python, and Swift With Examples

In this quick tutorial, we’ll learn how to quickly search a part of a string in an Array. We’ll be demonstrating the examples in Java, Python, and Swift.

The straightforward way to check whether a substring exists in any of the array elements is looping through the array elements. But in the next sections, we’ll use different approaches which are far shorter, cleaner and readable.

Substring in an Array Using Java

Using the Java 8 Stream API we can lookup if any substring is present in the array.

In the above code, we’ve created two methods. One to check if the substring exists. Other to return the matching substring.

anyMatch returns any of the substrings that got matched. No particular order.
Similarly, findAny returns any of the array elements that got matched. The value is returned as an Optional String.

The output of the above is:

Check For Substrings In Array Java

 

Check For Substrings In Array Java

Checking for Substring in Array Using Python

We can use Python list comprehension to check if the array contains substring or not.

any returns true if any of the substrings is present in the array.

To print the matched substring we use next.

next throws StopIteration if the condition was not matched at all.

Using Swift to check if array contains substring

Swift has been increasingly gaining popularity.

The below code snippet is a validation of that.

array.contains(where: string.contains) returns us a boolean if the array contains a substring of the string.

The output of the above code is :

Check For Substrings In Array Java

 

Check For Substrings In Array Swift

That sums up this tutorial. We have covered an interesting problem in Java, Python, and Swift.

By admin

Leave a Reply