Java Program to print all substrings of a given string
Program
import java.util.Scanner;
public class SubstringsOfString {
public String[] getSubstrings(String string)
{
int len = string.length();
int temp = 0;
String arrSubset[] = new String[len*(len+1)/2];
for(int i = 0; i < len; i++) {
for(int j = i; j < len; j++) {
arrSubset[temp] = string.substring(i, j+1);
temp++;
}
}
return arrSubset;
}
public static void main(String[] args){
SubstringsOfString substringsOfString = new SubstringsOfString();
Scanner reader = new Scanner(System.in);
System.out.print("Enter a string to get all substrings: ");
String enteredString = reader.nextLine();
String subsets[] = substringsOfString.getSubstrings(enteredString);
System.out.println("Substring of a given String are ");
for(int i = 0; i < subsets.length; i++) {
System.out.println(subsets[i]);
}
}
}
This program generates and prints all substrings of a given string.
-
Input:
- The program prompts the user to enter a string.
-
Logic:
- A substring is a contiguous sequence of characters within a string.
- For a string of length
n
, there aren*(n+1)/2
substrings. - Example:
- For "abc":
- Substrings: "a", "b", "c", "ab", "bc", "abc".
- For "abc":
-
Steps:
- Calculate the total number of substrings (
n*(n+1)/2
) and initialize an arrayarrSubset
to store them. - Use two nested loops:
- Outer loop: Fix the starting point of the substring (
i
). - Inner loop: Fix the ending point (
j
). - Extract the substring using
substring(i, j+1)
.
- Outer loop: Fix the starting point of the substring (
- Add each substring to the array.
- Calculate the total number of substrings (
-
Output:
- Iterate through the array and print all stored substrings.
-
Key Methods:
substring(start, end)
: Returns a substring from indexstart
toend-1
.- Dynamic Array Indexing: The variable
temp
is used to track the position in thearrSubset
array.
-
Example Execution:
- Input:
Enter a string to get all substrings: abc
- Process:
- Substrings generated:
- "a", "b", "c", "ab", "bc", "abc"
- Substrings generated:
- Output:
Substring of a given String are a b c ab bc abc
- Input:
-
Complexity:
- Time Complexity: O(n²) due to the nested loops.
- Space Complexity: O(n²) for storing substrings.
Features:
- Flexible Input:
- Works for any string, including alphanumeric and special characters.
- Array Storage:
- Allows access to all substrings for further processing.
Use Case:
- Text analysis, such as finding patterns or matches.
- Educational purposes to understand substring generation logic.
Output
$ javac SubstringsOfString.java
$ java SubstringsOfString
Enter a string to get all substrings: World
Substring of a given String are
W
Wo
Wor
Worl
World
o
or
orl
orld
r
rl
rld
l
ld
d