Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 42: Write a Java program to display all the substrings of a string.

SubString.java

import java.util.Scanner;

public class SubString
{
	//Method to print all sub strings of a string.
	public static void printSubstrings(String str)
	{
		for(int i=0; i < str.length();i++)
		{
			for(int j=i; j < str.length();j++)
			{
				System.out.println(str.substring(i,j+1));
			}
		}
	}

	//Main Method
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string");
		String str = s.nextLine();

		System.out.println("All substrings ");
		SubString.printSubstrings(str);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.