我有一个应该扫描字符串的函数,如果字符串包含诅咒字则返回true,否则返回false。
public static boolean isBad(String s) {
//cussWords is a previously defined arraylist containing all possible spellings of all swear words (Loaded from a utf8 encoded file if that matters)
s = s.replaceAll("[^A-Za-z0-9 ]", "").toLowerCase();
String[] arr = s.split(" ");
for (String str : arr) { //Break sentence into words and check each word
str = str.trim();
if (cussWords.contains(str)){ //Check if it is bad using ArrayList.contains function
System.out.printf("\"%s\" contains a bad word.\n",s);
return true;
}
if (badWords[hash(str)] != null) { //Check if it is bad using hash table
System.out.printf("'%s' contains bad word: %s|%s\n", s, badWords[hash(str)], str);
return true;
}
}
System.out.printf("'%s' does not contain any bad words.\n", s);
return false;
}
输入是硬编码的
System.out.println(cussWords.contains(*swear word*));
或
System.out.println(isBad(*sentence with swear word*));
输出正确,但在具有动态输入的服务器上运行时,该函数始终返回false。我花了几个小时独立地测试每个组件到这个功能,每个部分都独立工作,但是当它们放在一起时它们没有。我不知道代码是否可能已损坏,或者我错过了什么。
我在这里调用函数
if (isCensored) {
while (Dictionary.isBad(response)) {
response = db.fetchResponse(db.all.get(r.nextInt(db.all.size()))); //db.all is an arraylist containing all possible responses stored in the database (It's a chat bot)
}
}
以下是问题的要点(在我的代码中,它没有被审查)
System.out.println(wordSet.contains("f***")); //Returns true
for (String str : arr) {
str = str.trim();
System.out.println(str.equals("f***")); //Returns true
if (wordSet.contains(str)){ //Returns false
System.out.printf("\"%s\" contains a bad word.\n",s);
return true;
}
}