Write a Java program to find and display all substrings in string

By | 09.02.2017

Java program to find and display all substrings


This program find all substrings of a string and the prints them.

For example substrings of “cat” are :- “c”, “ca”, “cat”, “a”, “at” and “t”. substring method of String class is used to find substring.

Java code to print substrings of a string is given below.

 

SOURCE CODE ::

import java.util.Scanner;
 
public class Substrings_String
{
   public static void main(String args[])
   {
      String string, sub;
      int i, c, length;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Enter a string ");
      string  = in.nextLine();
 
      length = string.length();   
 
      System.out.println("Substrings of \""+string+"\" are :-");
 
      for( c = 0 ; c < length ; c++ )
      {
         for( i = 1 ; i <= length - c ; i++ )
         {
            sub = string.substring(c, c+i);
            System.out.println(sub);
         }
      }
   }
}

 

OUTPUT ::

 

Enter a string 
codez
Substrings of "codez" are :-
c
co
cod
code
codez
o
od
ode
odez
d
de
dez
e
ez
z

 

2 2 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments