【问题标题】:How to use contains and equalsIgnoreCase in string如何在字符串中使用 contains 和 equalsIgnoreCase
【发布时间】:2013-02-20 04:27:49
【问题描述】:

有没有办法在不区分大小写的情况下检查字符串是否包含某些内容?

例如:(此代码无效,只是为了让您对我的问题有一个基本的了解)

String text = "I love ponies";

if(text.contains().equalsIgnoreCase("love") {
    // do something
}

编辑: -------- 还是不行

哦,原来它不起作用。这是我正在使用的。 (这是一个游戏的诅咒过滤器)

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.");
    }
}

它适用于小写而不是大写。

【问题讨论】:

  • 由于您是 StackOverflow 的新手,请不要忘记mark the best option as the answer
  • 它仍然无法正常工作,因为您没有正确阅读答案。如果您想使用这种风格,请再次阅读 Anubhooti Pareek 的答案。你需要 event.getMessage().toLowerCase().contains(otherString.toLowerCase())
  • 另外,如果你打算过滤掉所有不好的词,并将它们硬编码到 if 语句中,你最终会得到一个非常大的条件......

标签: java


【解决方案1】:
return text.toLowerCase().contains(s2.toLowerCase());

或者另一种方式是

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(text).find();

【讨论】:

  • 我喜欢第一个解决方案。非常顺利:)
【解决方案2】:

如果您使用来自Apache Commons 库的StringUtils#containsIgnoreCase 会更容易

如果您不能添加第三方库,您仍然可以使用该代码,因为它是免费使用的。检查online source code

测试:

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"));
    }
}

输出:

true
true
true
true
false
false

【讨论】:

  • +1 如果 OP 不想添加第三方库,您提供的替代方案 :)
【解决方案3】:

如果区分大小写是您唯一的问题,请将所有内容都转换为小写

String text = "I love ponies";
String test = "LOVE";
if(text.toLowerCase().contains(test.toLowerCase()))
{
//your code
}

更新: 供您使用:

event.getMessage().toLowerCase().contains("douche".toLowerCase())

在所有条件下

【讨论】:

    【解决方案4】:

    你可以像这样检查两次

    text.contains(s);
    text.contains(s.toLowerCase());
    

    【讨论】:

    • 这是错误的:s = "aBc"text = "AbC"Both will be false.
    • 我知道这很简单,只是我过于复杂了。大声笑
    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2013-07-05
    • 2015-06-13
    相关资源
    最近更新 更多