Explain Codes LogoExplain Codes Logo

How to use string.startsWith() method ignoring the case?

java
prompt-engineering
functions
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

Case-insensitive comparison using toLowerCase() on both strings before startsWith():

// If Tarzan wrote Java code: boolean startsWithIgnoreCase = str.toLowerCase().startsWith(prefix.toLowerCase());

This transforms both str and prefix to lower case, effectively bypassing the case sensitivity.

Bypass case-sensitivity with regionMatches()

regionMatches() offers an out-of-the-box solution for comparing specific regions of strings in a case-insensitive way:

// Spoiler: Java wins again boolean startsWithIgnoreCase = str.regionMatches(true, 0, prefix, 0, prefix.length());

The first parameter (ignoreCase) specifies case-insensitive comparison.

Prefix magic with regex

Regular expressions provide powerful tools for pattern matching. We can easily perform a case-insensitive prefix check:

// Did anyone say regex magic? boolean startsWithIgnoreCase = str.matches("(?i)" + Pattern.quote(prefix) + ".*");

The Pattern.quote() ensures special characters behave normally during string encounters.

Good guy Apache Commons Lang

Apache Commons Lang library saves the day with StringUtils.startsWithIgnoreCase(). Offers a straightforward approach:

// StringUtils for the win! boolean startsWithIgnoreCase = StringUtils.startsWithIgnoreCase(str, prefix);

To utilize this, you have to include Apache Commons Lang in your project dependencies.

Embracing Unicode and locales

You might encounter Unicode strings, toLowerCase(Locale.ENGLISH) ensures case conversions are accurate:

// Java speaks more languages than the UN boolean startsWithIgnoreCase = str.toLowerCase(Locale.ENGLISH).startsWith(prefix.toLowerCase(Locale.ENGLISH));

Locale-sensitive methods are saviours when characters escape the ASCII range.

Watch out for pitfalls

Converting the entire string to lower or upper case for comparisons can lead to performance overhead with large strings.

Even Java needs to take a breather sometimes, you might want to consider using regionMatches() or StringUtils.startsWithIgnoreCase() instead.

Checking against multiple prefixes

If you need to compare a string with multiple prefixes, use the Java 8 Stream for a swell and scalable solution:

List<String> prefixes = Arrays.asList("baseball", "basketball", "soccer"); // Multitasking like a pro boolean startsWithAnyIgnoreCase = prefixes.stream() .anyMatch(prefix -> str.regionMatches(true, 0, prefix, 0, prefix.length()));

This method completely disregards the case while checking for prefixes.