Sunday 30 April 2017

java - What is the alternative for String.contains method that is case insensitive?




While reading the line as a string from a file and string.contains("someexamplestring") will return the output of the case sensitive string.



If there is "someExampleString" in line, it's not returning.



How to identify a string in a case-insensitive manner?


Answer



Actually, this is a duplicate of How to check if a String contains another String in a case insensitive manner in Java?







If you've simpler requirements and are dealing with English letters only, you can follow the below answer.



You should do string.toLowerCase().contains("someExampleString".toLowerCase());.



Read more about public String toLowerCase() from Java SE Documentation.



Also, as hinted by Artur Biesiadowski in the comment section of the question, re-iterating it here :





Regarding all the answers suggesting toLowerCase/toUpperCase - be
careful if you go outside of ASCII space
. There are some languages
where going lower to upper and back (or other way around) is not
consistent. Turkish with its dotless 'i' comes to mind : Dotted and
dotless I








Also, to make it safer, you may use another method toLowerCase(Locale.English) and override the locale to English always. But, the limitation being you are not internationalized any longer.



string.toLowerCase(Locale.English).contains("someExampleString".toLowerCase(Locale.English));

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...