Java
String Manipulation
Programming
Case Insensitive Comparison
Coding Tutorial

How to check if a String contains another String in a case insensitive manner in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, strings are sequences of characters used for storing text. A common task when dealing with strings is to check whether one string contains another. This process can often require a case-insensitive comparison, meaning the comparison does not consider whether letters are uppercase or lowercase. Accomplishing this requires several approaches, each suited to particular situations or developer preferences.

Using String.toLowerCase() or String.toUpperCase()

One straightforward method to perform a case-insensitive check if one string contains another is by converting both strings to the same case (either lower or upper) before performing the check. This can be done using String.toLowerCase() or String.toUpperCase(). Here is how it can be implemented:

java
1public class StringComparison {
2    public static boolean containsIgnoreCase(String src, String what) {
3        if (src == null || what == null) return false;
4        return src.toLowerCase().contains(what.toLowerCase());
5    }
6
7    public static void main(String[] args) {
8        String original = "Hello, World!";
9        String substring = "hello";
10        boolean result = containsIgnoreCase(original, substring);
11        System.out.println("Contains substring: " + result);
12    }
13}

Using Pattern and Matcher with Regular Expressions

For a more robust and flexible solution, Java’s Pattern and Matcher classes from the java.util.regex package can be used. These classes support more complex matching operations, including case-insensitive matching using regex patterns. Here is an example of how this can be implemented:

java
1import java.util.regex.Pattern;
2import java.util.regex.Matcher;
3
4public class RegexExample {
5    public static boolean containsIgnoreCaseRegex(String src, String what) {
6        if (src == null || what == null) return false;
7        Pattern pattern = Pattern.compile(Pattern.quote(what), Pattern.CASE_INSENSITIVE);
8        Matcher matcher = pattern.matcher(src);
9        return matcher.find();
10    }
11
12    public static void main(String[] args) {
13        String original = "Java is fun!";
14        String substring = "JAVA";
15        boolean result = containsIgnoreCaseRegex(original, substring);
16        System.out.println("Contains substring: " + result);
17    }
18}

In the above example, Pattern.CASE_INSENSITIVE is used to perform a case-insensitive match. The Pattern.quote method ensures that special characters in the substring are treated as literals rather than regex operators.

Wrapping Apache Commons Lang StringUtils

Another alternative is using third-party libraries such as Apache Commons Lang which provides utility methods for working with strings. The StringUtils class offers a method called containsIgnoreCase which internally handles case transformations or regex matches for you:

java
1import org.apache.commons.lang3.StringUtils;
2
3public class StringUtilsExample {
4    public static void main(String[] args) {
5        String original = "Sample text for testing";
6        String substring = "TEXT";
7        boolean result = StringUtils.containsIgnoreCase(original, substring);
8        System.out.println("Contains substring: " + result);
9    }
10}

Performance Considerations

When choosing which method to use, consider the following factors:

  1. Simplicity vs Flexibility: Methods using String.toLowerCase() are simpler but using Pattern and Matcher offers more flexibility for complex matching patterns.
  2. Performance: Converting strings to a common case might create temporary strings and use more memory, whereas regular expressions can be optimized but might be slower for simple cases.
  3. Third-party Dependencies: Using libraries like Apache Commons Lang introduces external dependencies which may be undesirable for smaller projects or applications sensitive to bloat.

Summary

MethodCase SensitivityComplexityExternal Dependencies
toLowerCase()/toUpperCase()Handled manuallyLowNo
Pattern and MatcherBuilt-inHighNo
Apache Commons Lang StringUtilsBuilt-inLowYes

In conclusion, Java offers multiple ways to check if a string contains another string in a case-insensitive manner. The best method depends on the specific requirements of the project, such as performance constraints, complexity of the string comparison, and willingness to use third-party libraries. Developers should evaluate the trade-offs associated with each method to choose the most appropriate for their needs.


Course illustration
Course illustration

All Rights Reserved.