How to check if a String contains another String in a case insensitive manner in Java?
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
Ignore case for 'contains' for a string in Java
You need to convert both the strings to the same case before using contains
s.toLowerCase().contains("ABCD".toLowerCase());
String contains - ignore case
You can use
org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
CharSequence searchStr);
Checks if CharSequence contains a search CharSequence irrespective of
case, handling null. Case-insensitivity is defined as by
String.equalsIgnoreCase(String).A null CharSequence will return false.
This one will be better than regex as regex is always expensive in terms of performance.
For official doc, refer to : StringUtils.containsIgnoreCase
Update :
If you are among the ones who
- don't want to use Apache commons library
- don't want to go with the expensive
regex/Pattern
based solutions, - don't want to create additional string object by using
toLowerCase
,
you can implement your own custom containsIgnoreCase
using java.lang.String.regionMatches
public boolean regionMatches(boolean ignoreCase,
int toffset,
String other,
int ooffset,
int len)
ignoreCase
: if true, ignores case when comparing characters.
public static boolean containsIgnoreCase(String str, String searchStr) {
if(str == null || searchStr == null) return false;
final int length = searchStr.length();
if (length == 0)
return true;
for (int i = str.length() - length; i >= 0; i--) {
if (str.regionMatches(true, i, searchStr, 0, length))
return true;
}
return false;
}
Can we check if string contains in another string with case insensitive?
Just lowercase both strings and then use contains()
:
for (int i = 0; i < itemsList.size(); i++) {
if (matching.toLowerCase().contains(itemsList.get(i).toLowerCase())) {
item = itemsList.get(i).trim();
break;
}
}
In Java, how do I check if a string contains a substring (ignoring case)?
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.
My input here need to be not case-sensitive. I'll show you my code please help, I have zero idea how to do it
Should make the string entirely to lower case or upper case. Use this while taking input:
s = sc.nextLine().toLowerCase();
and also:
x = sc.nextLine().toLowerCase();
The complete main method:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s, x;
System.out.print("Enter a sentence: ");
s = sc.nextLine().toLowerCase();
int vowel=0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
vowel++;
}
System.out.println("There are "+ vowel + " vowels in the sentence");
System.out.print("\nEnter a substring that you want to search: ");
x = sc.nextLine().toLowerCase();
boolean check = s.contains(x);
if (check){
System.out.println("There is a substring '" + (x.toUpperCase()) + "' in the sentence");
}
else
System.out.println("There is no substring '" + x + "' in the sentence");
System.out.println("\nThe entered sentence in uppercase characters.");
System.out.println(s.toUpperCase());
}
What is the alternative for String.contains method that is case insensitive?
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));
Option to ignore case with .contains method?
I'm guessing you mean ignoring case when searching in a string?
I don't know any, but you could try to convert the string to search into either to lower or to upper case, then search.
// s is the String to search into, and seq the sequence you are searching for.
bool doesContain = s.toLowerCase().contains(seq);
Edit:
As Ryan Schipper suggested, you can also (and probably would be better off) do seq.toLowerCase(), depending on your situation.
Check 2 strings without case sensitivity or use equalsIgnoreCase method
You can use
Map<String, String> listOfActions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
Other solutions can be Apache's CaseInsensitiveMap or Spring's LinkedCaseInsensitiveMap.
Please see https://www.baeldung.com/java-map-with-case-insensitive-keys for more details about these solutions.
Search for String case-insensitive
If you really need to use the code you posted, you just push both items to lowercase and then do the comparison.
string searchLower = search.toLowerCase();
string nameLower = name.toLowerCase();
boolean isIncluded = searchLower.startsWith(nameLower) && searchLower.endsWith(nameLower);
Otherwise, if you're actually trying to find if name
is contained in your search
. Then you can use org.apache.commons.lang3.StringUtils
from the Apache Commons library.
boolean isIncluded = StringUtils.containsIgnoreCase(search, name);
Related Topics
Want Current Date and Time in "Dd/Mm/Yyyy Hh:Mm:Ss.Ss" Format
Difference Between Wait() and Sleep()
Java: Convert List≪String≫ to a Join()D String
Does a Lambda Expression Create an Object on the Heap Every Time It's Executed
Quality of Image After Resize Very Low - Java
Do We Have Any Generic Function to Check If Page Has Completely Loaded in Selenium
Received Fatal Alert: Handshake_Failure Through Sslhandshakeexception
Is There a Concise Way to Iterate Over a Stream With Indices in Java 8
How to Remove Objects from an Array in Java
Nullpointerexception When Creating an Array of Objects
How to Call One Constructor from Another in Java
Java 8 Lambda Function That Throws Exception
Java Process With Input/Output Stream