Find Strings Containing a Substring in an Array

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

  1. Traverse the Array:
    • Iterate through each string in the array.
  2. Check for Substring:
    • Use the contains method of the String class to check if the current string contains the given substring.
  3. Collect Results:
    • Add strings that contain the substring to a result list.
  4. 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:

  1. Input Array and Substring:
    • The array words contains the strings to be checked, and substring is the substring to search for.
  2. Check for Substring:
    • Use the contains method to check if the current string contains the substring.
  3. Add to Results:
    • If the condition is true, add the string to the result list.
  4. 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).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *