In this article, we will learn how to write a Java program to find all strings in an array that contain a given substring. This exercise is helpful for practicing string manipulation and array traversal in Java.
Problem statement:
We are given an array of strings and a specific substring. The task is to identify and return all strings in the array that contain the given substring.
Approach to Solve the Problem
- Traverse the Array:
- Iterate through each string in the array.
- Check for Substring:
- Use the
contains
method of theString
class to check if the current string contains the given substring.
- Use the
- Collect Results:
- Add strings that contain the substring to a result list.
- Display Results:
- Print all strings that contain the substring.
Java program to find strings containing a substring in an Array
Here is the Java program to solve the problem:
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.List;
public class StringsContainingSubstring {
public static void main(String[] args) {
// Input array of strings
String[] words = { "apple", "banana", "grape", "pineapple" };
String substring = "apple";
// Call the method to find strings containing the substring
List<String> containingStrings = findStringsContainingSubstring(words, substring);
// Display the results
System.out.println(
"Strings containing the substring \"" + substring + "\": " + String.join(", ", containingStrings));
}
// Method to find strings containing a specific substring
public static List<String> findStringsContainingSubstring(String[] words, String substring) {
List<String> result = new ArrayList<>();
// Check each string in the array
for (String word : words) {
if (word.contains(substring)) {
result.add(word);
}
}
return result;
}
}
OUTPUT:
Strings containing the substring “apple”: apple, pineapple
Code Explanation:
- Input Array and Substring:
- The array
words
contains the strings to be checked, andsubstring
is the substring to search for.
- The array
- Check for Substring:
- Use the
contains
method to check if the current string contains the substring.
- Use the
- Add to Results:
- If the condition is true, add the string to the result list.
- Output Results:
- The program prints all strings that contain the substring.
Conclusion
This program demonstrates a simple and efficient way to find strings containing a specific substring in an array. It strengthens your understanding of string manipulation and conditional checks in Java.
You can learn the Top 20 string array programs for interview preparation (Click here).