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

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet