Algorithm


  1. Input:

    • Accept the main string (mainString) and the substring (subString) as input.
  2. Initialization:

    • Initialize two variables: mainLength to store the length of the main string, and subLength to store the length of the substring.
  3. Loop through the main string:

    • Use a loop to iterate through each character of the main string from index 0 to mainLength - subLength.
  4. Check for substring match:

    • For each index i in the loop, compare the substring starting from index i in the main string with the given substring.
    • If they match, the substring is found in the main string.
  5. Output:

    • If a match is found, print or return a message indicating that the substring is present.
    • If no match is found after iterating through the entire string, print or return a message indicating that the substring is not present.

 

Code Examples

#1 Code Example- Check if a string contains a substring using contains()

Code - Java Programming

class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Programiz";
    String str1 = "Programiz";
    String str2 = "Programming";

    // check if name is present in txt
    // using contains()
    boolean result = txt.contains(str1);
    if(result) {
      System.out.println(str1 + " is present in the string.");
    }
    else {
      System.out.println(str1 + " is not present in the string.");
    }

    result = txt.contains(str2);
    if(result) {
      System.out.println(str2 + " is present in the string.");
    }
    else {
      System.out.println(str2 + " is not present in the string.");
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Programiz is present in the string.
Programming is not present in the string.

#2 Code Example- Check if a string contains a substring using indexOf()

Code - Java Programming

class Main {
  public static void main(String[] args) {
    // create a string
    String txt = "This is Programiz";
    String str1 = "Programiz";
    String str2 = "Programming";

    // check if str1 is present in txt
    // using indexOf()
    int result = txt.indexOf(str1);
    if(result == -1) {
      System.out.println(str1 + " not is present in the string.");
    }
    else {
      System.out.println(str1 + " is present in the string.");
    }

    // check if str2 is present in txt
    // using indexOf()
    result = txt.indexOf(str2);
    if(result == -1) {
      System.out.println(str2 + " is not present in the string.");
    }
    else {
      System.out.println(str2 + " is present in the string.");
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Programiz is present in the string.
Programming is not present in the string.
Advertisements

Demonstration


Java Programing Example to Check if a string contains a substring-DevsEnv