Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]

I have two Strings, str1 and str2. How do I check if str2 is contained within str1, ignoring case?

like image 912
trinity Avatar asked Feb 16 '10 17:02

trinity


People also ask

How do you check if a string contains a substring in Java?

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.

Does string contain check case-insensitive Java?

Yes, contains is case sensitive. You can use java. util.

How do you check if a string contains a substring twice?

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.

How do you ignore a case in Java?

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.


1 Answers

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.

like image 66
Igor Artamonov Avatar answered Oct 22 '22 09:10

Igor Artamonov