A substring is a contiguous sequence of characters within a string. Every non-empty string is a substring of itself. In this article, we will learn how to find all possible non-empty substrings of a given string.
- Define a substring as a contiguous sequence of characters from the original string.
- Clearly state that the program generates non-empty substrings.
Illustration:
Input: bat
Output: b
ba
bat
a
at
t
For a string of length n, the total number of non-empty substrings is:
n * (n + 1) / 2
Approach
- Traverse the string using an outer loop to select the starting index.
- Use an inner loop to select the ending index.
- Generate each substring using the substring() method.
- Store each substring in an ArrayList.
- Print all the generated substrings.
import java.util.ArrayList;
public class Geeks {
// Method to find all substrings
static ArrayList<String> findSubstrings(String str) {
ArrayList<String> substrings = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
// Add substring from index i to j - 1
substrings.add(str.substring(i, j));
}
}
return substrings;
}
public static void main(String[] args) {
String str = "The Cat";
ArrayList<String> substrings = findSubstrings(str);
System.out.println("All substrings:");
for (String substring : substrings) {
System.out.println(substring);
}
}
}
Output
All substrings: T Th The The The C The Ca The Cat h he he he C he Ca he Cat e e e C e Ca e Cat C Ca Cat C Ca Cat a at t
Explanation
- The outer loop selects the starting index of each substring.
- The inner loop selects the ending index.
- substring(i, j) extracts characters from index i to j - 1.
- Each generated substring is added to the ArrayList.
- For "The Cat", the program generates 28 non-empty substrings.