Find all substrings of a String in java

In this example, You learn about java program to find all substrings of a String. 

Here you learn all substrings of string in Java, You are given a string and the task of the program to find all substrings of a String.

Java Program to find all substrings of a String

import java.util.Scanner;

public class SubstringsOfAString
{
 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 to print it's all substrings");
    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 to print it's all substrings
abbc

Substrings of "abbc" are :-
a
ab
abb
abbc
b
bb
bbc
b
bc
c

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form