I have two String
s, str1
and str2
. How do I check if str2
is contained within str1
, ignoring case?
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Yes, contains is case sensitive. You can use java. util.
Check If Substring Exists Twice In String You can check if the string contains a substring twice using the count() function available in the String class.
Java String equalsIgnoreCase() Method The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.
str1.toUpperCase().contains(str2.toUpperCase())
UPD:
Original answer was using toLowerCase()
method. But as some people correctly noticed, there are some exceptions in Unicode and it's better to use toUpperCase()
. Because:
There are languages knowing more than one lower case variant for one upper case variant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With