Java program to check if a Substring is present in a given String


A substring is a part of a string and it can be checked if a particular substring is present in the given string or not. An example of this is given as follows −

String = The sunset is beautiful
Substring = sunset

This substring is present in the string.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Example {
   public static void main(String args[]) {
      String str = "Apples are red";
      String substr = "are";
      int n1 = str.length();
      int n2 = substr.length();
      System.out.println("String: " + str);
      System.out.println("Substring: " + substr);
      for (int i = 0; i <= n1 - n2; i++) {
         int j;
         for (j = 0; j < n2; j++) {
            if (str.charAt(i + j) != substr.charAt(j))
               break;
         }
         if (j == n2) {
            System.out.println("The substring is present in the string at index " + i);
            return;
         }
      }
      System.out.println("The substring is not present in the string");
   }
}

Output

String: Apples are red
Substring: are
The substring is present in the string at index 7

Now let us understand the above program.

First, the string and substring are printed. The code snippet that demonstrates this is given as follows −

String str = "Apples are red";
String substr = "are";
int n1 = str.length();
int n2 = substr.length();
System.out.println("String: " + str);
System.out.println("Substring: " + substr);

Then a for loop is used to find if the substring is a part of the given string or not. If it is, then this is printed and the index at which the substring starts in the string is also specified. Then the main() function returns. The code snippet that demonstrates this is given as follows −

for (int i = 0; i <= n1 - n2; i++) {
   int j;
   for (j = 0; j < n2; j++) {
      if (str.charAt(i + j) != substr.charAt(j))
         break;
      }
      if (j == n2) {
         System.out.println("The substring is present in the string at index " + i);
         return;
      }
   }
}

If the substring is not present in the string, then this is printed after the finishing of the for loop. The code snippet that demonstrates this is given as follows −

System.out.println("The substring is not present in the string");

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements