Program to find all substrings of a string and print them. For example substrings of "fun" are:- "f", "fu", "fun", "u", "un","n". Use substring method of String class to find substring

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are immutable. Strings are constant; their values cannot be changed after they are created. For example:
String str = "abc";    // Creates a string literal
OR
String str = new String("abc");

Here we have used the String class's method length( ) which returns the length of string. The method substring(int beginIndex, int endIndex) returns a new string that is a substring of this string. We have created a string and divide that string into subparts which are shown in output.

PROGRAM
import java.util.Scanner;

public class SubStringsOfString {

 public static void main(String[] args) {

  Scanner s = new Scanner(System.in);
  System.out.println("Enter some string:");
  String str = s.nextLine();
  System.out.println("Substrings of '"+ str + "' are... ");
  int length = str.length();
  
  for(int a=0; a<length; a++)
  {
   for(int i=1; i<=(length-a);i++)
   {
    System.out.println(str.substring(a,i+a));
   }
  }
 }
}
OUTPUT
C:\>javac SubStringsOfString.java
C:\>java SubStringsOfString
Enter some string:
fun
Substrings of 'fun' are... 
f
fu
fun
u
un
n

Comments

Popular posts from this blog

Develop an Android application to display “Hello World!” on screen

Program to design an applet which draws a circle (having color BLUE) inside a triangle (having color YELLOW)

Build a Simple Android App to Display Student Details