In Java, how do I check if a string contains a substring (ignoring case)?
To check if a string contains a substring (ignoring case) in Java, you can use the contains
method of the String
class and the equalsIgnoreCase
method.
The contains
method returns true
if the string contains the specified substring, and false
if it does not. The equalsIgnoreCase
method compares two strings for equality, ignoring case.
Here's an example of how you can use the contains
and equalsIgnoreCase
methods to check if a string contains a substring (ignoring case):
public class Main {
public static void main(String[] args) {
String str = "Hello World!";
// Check if the string contains the substring "world" (ignoring case)
if (str.toLowerCase().contains("world")) {
System.out.println("Match found!");
} else {
System.out.println("Match not found.");
}
// Check if the string is equal to the substring "hello world" (ignoring case)
if (str.equalsIgnoreCase("hello world")) {
System.out.println("Match found!");
} else {
System.out.println("Match not found.");
}
}
}
This code will print "Match found!" for both checks.
I hope this helps! Let me know if you have any other questions.