Finding all substrings of given string in JAVA

How to find all possible substrings for a given string in java. Java step by step code with explanation to find the sub string of a given string.

What is Substring ?

Substring is basically part of string considering the elements of original string in continous order.

Examples:

Given String is “ABC”.

If you wish to find sub strings for this then possible combinations are

A

AB

ABC

B

BC

C

So these are possible substring of string “ABC”.

Example 2:

Given string is “ABCD”, then possible sub strings are….

A, AB, ABC, ABCD

B,BC,BCD,

C,CD

D

SO these are all the possible sub string for “ABCD“.

Algorithm to write JAVA Code

  • Take the input from user like string input
  • Use two for loops for iterating through elements of string
  • first loop will run from first element at (Index 0) to last element at (Index string.length).
  • The second for loop will start 1 position ahead of first element that is j=i+1.
  • In same order j will be running upto last element in given string
  • Use substring mehtod of string class to get a substring by specifying the starting and ending indicec.
  • print the substrings to output screen

JAVA CODE

package arrayPrograms;

class Demo1 {

	public static void main(String[] args) {
		
		
		String s="ABC";
		for(int i=0;i<s.length();i++) {
			
			for(int j=i+1;j<=s.length();j++) {
				System.out.println(s.substring(i, j));
			}
		}
		

	}

}

Watch step by step explanation for above code on our channel

Similar Posts You Might Like

Off Campus Coding Question on Arrays

Dynamic Programming HACKER EARTH questions

What is Jagged Array In Java

Rotate Array Elements towards Right Side

1 thought on “Finding all substrings of given string in JAVA”

  1. Pingback: Hacker Earth Coding Question with Solution - Is It Actually

Leave a Comment

Your email address will not be published. Required fields are marked *