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.


import java.util.Arrays;
import java.util.Optional;
public class SubStringChecker{
     public static void main(String []args){
        System.out.println("Hello World");
        String[] array = {"abc","def", "ghi"};
        String input = "abcdefghi";
        boolean stringExists = substringExistsInArray(input, array);
        System.out.println(stringExists);
        String input2 = "acdfhi";
        stringExists = substringExistsInArray(input2, array);
        System.out.println(stringExists);
        System.out.println(getFirstMatchingSubstring(input, array));
        System.out.println(getFirstMatchingSubstring(input2, array));
     }
     public static boolean substringExistsInArray(String inputStr, String[] items) {
        return Arrays.stream(items).parallel().anyMatch(inputStr::contains);
     }
     public static Optional getFirstMatchingSubstring(String inputStr, String[] items) {
       return Arrays.stream(items).parallel().filter(inputStr::contains).findAny();
     }
}

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.


input1 = "abcdefghi"
array = ['abc', 'def', 'ghi']
result = any(sub in input1 for sub in array)
print("substring exists in the list for input1: " + str(result))
input2 = "acdfhi"
result = any(sub in input2 for sub in array)
print("substring exists in the list for input2: " + str(result))
matchingString = next(substring for substring in array if substring in input1)
print("substring that matched was "+matchingString)
#Output
"""
substring exists in the list for input1: True
substring exists in the list for input2: False
substring that matched was abc
"""

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.


import UIKit
let input1 = "abcdefghi"
let array = ["abc", "def", "ghi"]
let input1Matches = array.contains(where: input1.contains)
print("array contains input1 (input1Matches)")
let input2 = "acdfhi"
let input2Matches = array.contains(where: input2.contains)
print("array contains input2 (input2Matches)")

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

%d bloggers like this: