【问题标题】:Android Java Bad Words Filter [closed]Android Java 坏词过滤器 [关闭]
【发布时间】:2019-01-11 15:35:53
【问题描述】:

我想创建坏词过滤器。这是我的示例代码:

String name = "jack white";   // **NOT WORK** 
String name = "white";  // **WORK**
String lowername = name.toLowerCase();
String[] banned = { "name", "hello", "white"};

if (Arrays.asList(banned).contains(lowername)) {
true;
}

如果 name white 功能有效,但 name jack white、xxx white 或 white xxx 功能无效。

我想为用户cmets做一个坏词过滤器。

【问题讨论】:

  • 你能不能更详细地说明你想要什么。
  • 包含比较整个条目而不是部分
  • 这看起来像是一个复杂的问题。
  • 我建议查看模式和模式匹配器以及正则表达式。这些会有所帮助。
  • @chrylis:是的,当然。 thedailywtf.com/articles/The-Clbuttic-Mistake-

标签: java android arrays string filter


【解决方案1】:

试试这个..

static String string1 = "jack smith ran across the street";
static String string2 = "smith jumped";

public static boolean compareStrings(String one, String two){
    boolean helper = false;

    String[] string = one.split(" ");
    for (int i = 0; i < string.length; i++) {
        if (two.contains(string[i])) {
            helper = true;
            System.out.println(string[i]);
        }
    }

    return helper;

}

然后使用它...

System.out.println(compareStrings(string1, string2));

这将打印出来...

smith
true

【讨论】:

  • 您好,我只向数组发送一个字符串,如果数组上的字符串我需要 true。
  • 那很好......只需删除“跳跃”这个词。它仍然是真的……结果是真的,因为 smith 这个词包含在 string1 中
【解决方案2】:

您需要将输入的名称分解为单个单词,并根据禁用词检查每个单词: (旁注:在这里使用集合而不是数组会大大提高性能)

Set<String> banned = new HashSet<>(Arrays.asList("name", "hello", "white"));

boolean shouldBeBanned = 
    Arrays.stream(name.split("\\s")).map(String::toLowerCase).anyMatch(banned::contains);

编辑:
当然,同样的行为可以在没有 API 级别 24 的情况下实现,尽管它不会那么优雅:

boolean shouldBeBanned = false;
for (String word : name.split("\\s")) {
    if (banned.contains(word.toLowerCase()) {
        shouldBeBanned = true;
        break;
    }
}

【讨论】:

  • Arrays.stream 需要 API LEVEL 24。
  • @user1318741 确实如此。有关不需要 API 级别 24 的等效解决方案,请参阅我编辑的答案。
  • 字符串白色时工作,但白色或白色+任何东西都不起作用。 @Mureinik 我想禁止所有包含禁止词的内容。
【解决方案3】:

其实你做错了Arrays.asList(banned).contains(lowername)。看懂list.contains

我已经修改了您的代码,如下所示。

    String name = "jack white"; // **NOT WORK** 
    //String name = "white";  // **WORK**
    String lowername = name.toLowerCase();
    String[] banned = {"name", "hello", "white"};
    List<String> data = Arrays.asList(banned);
    boolean status = hasBannedWords(data,lowername);
    Log.d("TAG",""+status);

检查单词的单独方法。

private boolean hasBannedWords(List<String> data, String sentence) {
    for(String item: data) {
        if(sentence.contains(item)) {
            return true;
        }
    }
    return false;
}

【讨论】:

  • @user1318741 欢迎您,验证后请告诉我
  • Arrays.stream 需要 API LEVEL 24。我正在使用 API LEVEL 16 :)
  • @user1318741 查看更新后的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多