Find All Substrings of a String in Java with Example

In this tutorial, I will be sharing what is substring, programs for finding substrings of a String in java with examples. Let's dive deep into the topic.

What is a substring?

According to Wikipedia,

The contiguous sequence of characters within a String is called substring.
For example, "Awesome" is a substring of "Alive is Awesome". You should not confuse substring with subsequence. "Alive Awesome" is a subsequence of "Alive is Awesome".

Read Also: String Interview Questions

Let's understand the question first with examples:

InputString: abc

Output: a, b, c, ab, bc, abc

InputString: abcd

Output: a, ab, abc, abcd, b, bc, bcd, c, cd, d

Programs for finding substrings of a String in Java

There are two ways through which we can generate substrings of a String in java.

1. Using StringBuilder/StringBuffer class [Efficient]
2. Using String class substring() method [Easy]

1. Using StringBuilder/StringBuffer class

You can generate substrings of a String using StringBuilder/StringBuffer class in java. The time complexity will be O(n)2.

import java.util.Scanner;
public class JavaHungry {
public static void findSubstring(char[] input)
{
int length = input.length;
for (int i=0; i < length ; i++)
{
StringBuilder str = new StringBuilder();
str.append(input[i]);
for (int j=i+1; j <= length ; j++)
{
System.out.println(str);
if (j < length)
{
str.append(input[j]);
}
}
}
}

public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String inputString = in.next();
findSubstring(inputString.toCharArray());
}
}

Output:

substrings of a String in java output

2. Using substring() method

You can easily generate substrings of a String using String class substring() method. The time complexity will be O(n)3 since there are two for loops and substring() method has O(n) time complexity.

import java.util.Scanner;
public class JavaHungry {
public static void findSubstring(String input)
{
for(int i=0; i < input.length() ;i++)
{
for(int j=i+1; j <= input.length(); j++)
{
System.out.println(input.substring(i,j));
}
}
}

public static void main(String args[])
{
System.out.println("Enter any String: ");
Scanner in = new Scanner(System.in);
String inputString = in.next();
System.out.println("substrings of "+inputString+ " are :");
findSubstring(inputString);
}
}

Output:
Enter any String:
Alive
substrings of Alive are :
A
Al
Ali
Aliv
Alive
l
li
liv
live
i
iv
ive
v
ve
e


That's all for today, please mention in comments in case you have any questions related to the substrings of a String in java.

0 Comments