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

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
           
         }

       }
   }
}

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x