You are here

Java program to find all substrings of a string

Java program to find substrings of a string: This program find all substrings of a string and then prints them. For example, substrings of "fun" are: "f", "fu", "fun", "u", "un" and "n". The substring method of String class is used to find a substring. For a string of length n, there are (n(n+1))/2 non empty substrings and an empty string. Empty or NULL string is considered to be a substring of every string.

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class SubstringsOfAString
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       String string, sub;
  8.       int i, c, length;
  9.          
  10.       Scanner in = new Scanner(System.in);
  11.       System.out.println("Enter a string to print it's all substrings");
  12.       string  = in.nextLine();
  13.      
  14.       length = string.length();  
  15.  
  16.       System.out.println("Substrings of \""+string+"\" are:");
  17.      
  18.       for (c = 0; c < length; c++)
  19.       {
  20.          for(i = 1; i <= length - c; i++)
  21.          {
  22.             sub = string.substring(c, c+i);
  23.             System.out.println(sub);
  24.          }
  25.       }
  26.    }
  27. }

Output of program:
Output of Java program fo find all substrings of a string

Download Substrings of a string program class file.