string matching
array search
programming
code optimization
data structures

Test if a string contains any of the strings from an array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In many programming scenarios, especially in text processing and data analysis, it becomes crucial to determine whether a string contains any of the specified substrings from a list or array. This operation can be used in scenarios ranging from word filtering to tag matching. Depending on the programming language and the size of the data involved, different approaches can be used, each with its own advantages concerning performance and readability.

Basic Concepts

To check if a string contains any substrings from an array, we essentially look for matches of any elements within the given string. This often involves iterating over the list of substrings and checking for their presence in the target string using substring search functions provided by the language in use.

Common Techniques by Language

Python

Python provides an idiomatic way of performing this check using list comprehensions and the built-in any and in keywords.

Example:

python
1def contains_any_substring(string, substrings):
2    return any(substring in string for substring in substrings)
3
4# Usage
5target_string = "This is a sample test string."
6substrings = ["sample", "example", "test"]
7
8result = contains_any_substring(target_string, substrings)
9print(result)  # Output: True

JavaScript

JavaScript users can leverage the Array.prototype.some method combined with the String.prototype.includes method to achieve similar results.

Example:

javascript
1function containsAnySubstring(string, substrings) {
2    return substrings.some(substring => string.includes(substring));
3}
4
5// Usage
6const targetString = "This is a sample test string.";
7const substrings = ["sample", "example", "test"];
8
9const result = containsAnySubstring(targetString, substrings);
10console.log(result);  // Output: true

Java

In Java, using loops combined with the String.contains method provides a clear way to check for these conditions.

Example:

java
1import java.util.Arrays;
2import java.util.List;
3
4public class SubstringChecker {
5    public static boolean containsAnySubstring(String string, List<String> substrings) {
6        for (String substring : substrings) {
7            if (string.contains(substring)) {
8                return true;
9            }
10        }
11        return false;
12    }
13
14    public static void main(String[] args) {
15        String targetString = "This is a sample test string.";
16        List<String> substrings = Arrays.asList("sample", "example", "test");
17
18        boolean result = containsAnySubstring(targetString, substrings);
19        System.out.println(result);  // Output: true
20    }
21}

Performance Considerations

When implementing a substring check across a large dataset or when working with numerous strings in the array, it's essential to consider the underlying algorithmic complexity:

  • Naive Approach: Often, the basic approach of iterating over each element in the array and each character in the string can be costly, especially if the dataset is large.
  • Advanced Techniques: Algorithms and data structures like the Trie or Aho-Corasick algorithm can be used to improve search efficiency when dealing with large-scale text matching problems. Such techniques preprocess the array to optimize repeated searches.

Summary Table

Below is a table that summarizes the key aspects and best practices when checking for substrings in different programming environments:

LanguageCommon MethodPerformance ConsiderationNotes
Pythonany(sub in str)O(n×m)O(n \times m) (where n is the number of substrings and m is the average length of substrings)Simple, readable.
JavaScriptsome(sub => str.includes(sub))O(n×m)O(n \times m)Readability with ES6+ syntax.
Javaloops with String.containsO(n×m)O(n \times m)Verbose; best wrapped in a utility method.
AdvancedTrie, Aho-CorasickSub-linear time on repeated searchesRequires implementation overhead.

Additional Considerations

  • Case Sensitivity: It's important to decide whether the substring search should be case-sensitive. This can typically be adjusted by converting both the target string and array elements to lower case before the search begins.
  • Unicode and Encoding Issues: In multilingual applications, ensure that the text encoding (such as UTF-8) is consistently handled across both the target string and substrings.
  • Regular Expressions: In cases where the substrings have a pattern, regular expressions might offer a more dynamic solution, though they come with their own complexity.

Efficiently determining if a string contains any of a given set of substrings is a common task, and by using these different strategies, developers can optimize their applications for both performance and readability based on the specific requirements of the task at hand.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.