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.
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
- First get the length of the string using length function.
- Create a for loop which iterates over all the index positions of string.
- 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]