Java program to find all substrings of a string
Java program to find substrings of a string: This program finds 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. An empty or NULL string is considered to be a substring of every string.
Find substrings of a string in Java
import java.util.Scanner;
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 all its 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 of program: