Program to find all the substring using java

Question

Write a program to find all the substring within a string. Write an efficient code with less time complexity.

All the substring within a string

Logic

  • The logic is very simple, get the length of the string.
  • For each index of string print all the substrings possible starting from that index.
  • For example, if the all the substrings from index 0 is printed then increment the index and print the substrings starting from index 1.

Algorithm

  1. First get the length of the string using length function.
  2. Create a for loop which iterates over all the index positions of string.
  3. Create another inner for loop to print all possible combinations using substring function.

Program

[code lang=”java”]
class Substring
{
public static void main(String ar[])
{
String str= "hari";
int len = str.length();

for(int i=0; i<len;i++)
{
for(int j=i+1;j<=len;j++)
{
System.out.println(str.substring(i,j));// returns substring from i to j-1

}

}
}
}
[/code]

 

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.

Leave a Reply

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