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

 

3.5 4 votes
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments