Java 字符串匹配函数将无法正常工作
我有一个函数,它应该扫描一个字符串,如果字符串包含诅咒词,则返回true,否则返回falseJava 字符串匹配函数将无法正常工作,java,string,arraylist,hashtable,contains,Java,String,Arraylist,Hashtable,Contains,我有一个函数,它应该扫描一个字符串,如果字符串包含诅咒词,则返回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.
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*));
或
输出是正确的,但是当在服务器上使用动态输入运行时,函数总是返回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)
}
}
以下是问题的要点(在我的代码中它没有被审查)
您确定服务器上的脏话和坏话中有一些数据吗?介意在日志或标准输出中打印出它们的大小吗?您并没有显示如何调用
isBad()
来进行“动态输入”。这一点很重要,正如您所说,isBad()
在从测试调用时起作用。问题在于您如何读取动态输入。我已经在循环中打印了str的值,并且我已经验证了每个单词都正确地通过了循环。查看您在问题中输入的代码,这并没有达到预期效果,这确实令人惊讶。您可能应该使用调试器逐步完成代码。这将很快揭示出问题所在。
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;
}
}