Is there a way to check if a string contains something while not being case sensitive?
For example: (this code is invalid it's just for you to get a basic understanding of my question)
String text = "I love ponies";
if(text.contains().equalsIgnoreCase("love") {
// do something
}
EDIT: -------- Still not working
ooh, turns out it's not working. Here's what I'm using. (it's a curse filter for a game)
public void onChat(PlayerChatEvent event) {
Player player = event.getPlayer();
if (event.getMessage().contains("douche".toLowerCase()) || /* More words ... */) {
event.setCancelled(true);
player.sendMessage(ChatColor.GOLD + "[Midnight Blue] " + ChatColor.RED + "Please Don't Swear.");
}
}
It works with lowercase but not uppercase.
return text.toLowerCase().contains(s2.toLowerCase());
Or another way would be
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(text).find();
It would be easier if you use StringUtils#containsIgnoreCase
from Apache Commons library
If you can't add a third party library, you can still use the code because is free to use. Check the online source code.
Test:
public class QuestionABCD {
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
int len = searchStr.length();
int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(containsIgnoreCase("abc", "A"));
System.out.println(containsIgnoreCase("abc", "a"));
System.out.println(containsIgnoreCase("abc", "B"));
System.out.println(containsIgnoreCase("abc", "b"));
System.out.println(containsIgnoreCase("abc", "z"));
System.out.println(containsIgnoreCase("abc", "Z"));
}
}
Output:
true
true
true
true
false
false
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