How to ignore case when using startsWith and endsWith in Java?

How to ignore case when using startsWith and endsWith in Java?

To ignore case when using startsWith and endsWith in Java, you can convert the input strings and the target substrings to lowercase (or uppercase) before comparing them. Here's how you can do it:

Using toLowerCase:

String str = "Hello World";
String prefix = "he";
String suffix = "LD";

boolean startsWithIgnoreCase = str.toLowerCase().startsWith(prefix.toLowerCase());
boolean endsWithIgnoreCase = str.toLowerCase().endsWith(suffix.toLowerCase());

System.out.println("Starts with (ignore case): " + startsWithIgnoreCase);
System.out.println("Ends with (ignore case): " + endsWithIgnoreCase);

Using toUpperCase:

String str = "Hello World";
String prefix = "he";
String suffix = "LD";

boolean startsWithIgnoreCase = str.toUpperCase().startsWith(prefix.toUpperCase());
boolean endsWithIgnoreCase = str.toUpperCase().endsWith(suffix.toUpperCase());

System.out.println("Starts with (ignore case): " + startsWithIgnoreCase);
System.out.println("Ends with (ignore case): " + endsWithIgnoreCase);

Both approaches work by converting both the source string and the target prefix/suffix to the same case (either all lowercase or all uppercase) before performing the comparison. This ensures that the comparison is case-insensitive.


More Tags

python-turtle citations oracleclient auto-versioning oracle9i group-by regex boot big-o stomp

More Java Questions

More Everyday Utility Calculators

More Transportation Calculators

More Electrochemistry Calculators

More Weather Calculators