Skip to content

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, the standard solution is to convert the string to lowercase and use the contains method. Alternatively, you can use the regionMatches method for a more efficient case-insensitive check.

The contains method returns true if the string contains the specified substring, and false otherwise. The equalsIgnoreCase method compares two strings for exact equality, ignoring case, but does not support substring matching. For case-insensitive substring checks, regionMatches is often preferred for performance as it avoids creating a new string.

Here's an example of how you can use these methods to check if a string contains a substring (ignoring case):


java
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.");
    }

    // Alternative: Use regionMatches for case-insensitive substring checking
    // regionMatches(ignoreCase, toffset, other, ooffset, len)
    if (str.regionMatches(true, 0, "world", 0, 5)) {
      System.out.println("Match found (regionMatches)!");
    } 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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.