Java program to check if a string contains a substring
Here's an example Java program to check if a string contains a substring:
public class SubstringChecker { public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog"; if (containsSubstring(str, "fox")) { System.out.println("The string contains the substring 'fox'"); } else { System.out.println("The string does not contain the substring 'fox'"); } } public static boolean containsSubstring(String str, String substring) { // Check if the substring is null or empty if (substring == null || substring.isEmpty()) { return true; } // Check if the substring is longer than the string if (substring.length() > str.length()) { return false; } // Check if the substring is found in the string for (int i = 0; i <= str.length() - substring.length(); i++) { if (str.substring(i, i + substring.length()).equals(substring)) { return true; } } return false; } }
This program uses a containsSubstring
method that takes two strings as input: the first string is the main string to be checked, and the second string is the substring to be checked for. The method returns true
if the substring is found in the main string, and false
otherwise.
To check if the main string contains the substring, the containsSubstring
method first checks if the substring is null or empty, in which case it returns true
. It then checks if the length of the substring is greater than the length of the main string, in which case it returns false
.
If the length of the substring is less than or equal to the length of the main string, the method iterates over the characters of the main string using a for
loop, comparing each substring of the main string with the given substring using the equals
method. If the substring is found, the method returns true
.
In the main method, the containsSubstring
method is called with a sample string "The quick brown fox jumps over the lazy dog"
and a sample substring "fox"
. If the substring is found in the main string, the program prints a message indicating that the string contains the substring. Otherwise, it prints a message indicating that the string does not contain the substring.
Note that this program assumes that the substring is case-sensitive. If you want to make the comparison case-insensitive, you can convert both the main string and the substring to lowercase using the toLowerCase
method before comparing them.