Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use contains and equalsIgnoreCase in string

Tags:

java

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.

like image 841
Hayden Taylor Avatar asked Feb 20 '13 04:02

Hayden Taylor


2 Answers

return text.toLowerCase().contains(s2.toLowerCase());

Or another way would be

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(text).find();
like image 178
Anubhooti Pareek Avatar answered Oct 02 '22 14:10

Anubhooti Pareek


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
like image 25
Luiggi Mendoza Avatar answered Oct 02 '22 16:10

Luiggi Mendoza