我相信该程序适用于除一个以外的大多数情况。我在 indexOF() 中添加了空格,所以像 cathrine 和 dogsuit lammas 这样的词都会被认为是非亵渎的。我看到的唯一问题是用户是否以 cat/dog/llama 开头。猫!会显示为非亵渎,因为开始时没有空格,之后也没有空格,是否有一个 String 命令来散布东西,或者我完全走错了路?
import java.util.Scanner;
public class ProfanityFilter
{
public static void main(String[] args)
{
System.out.println (" welcome to the Profanity filter billboard service ");
System.out.println (" please enter a potential sign that contains the words \"cat\", \"dog\" or \"llama\"" );
Scanner keyboard = new Scanner (System.in);
String s1 = keyboard.nextLine();
s1 = s1.toLowerCase();
if (s1.indexOf(" cat ")!=-1 || s1.indexOf(" dog ") !=-1 || s1.indexOf(" llama ")!=-1)
System.out.println ("Profanity is in your Billboard");
else
System.out.println ("There is no profanity in your Billboard");
}
}
最佳答案
正则表达式来拯救!
if (s1.matches("^.*\\b(cat|dog|llama)\\b.*$"))
一些解释:
\b
表示字边界(a|b|c)
表示“a or b or c”
你可以从一个数组构造它:
String[] badWords = {"cat", "dog", "llama"};
String regex = "^.*\\b(" +
Arrays.toString(badWords).replace(", ", "|").replace("[", "").replace("]", "") +
")\\b.*$";
关于java - 我如何分离一个字符串,以便 "cat!"将是 "cat !",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464206/