[英]How do i seperate a String so that “cat!” will be “cat !”
I believe this program will work for most instances except one. 我相信该程序将适用于除一种情况以外的大多数情况。 I added spaces in indexOF() so words like cathrine and dogsuit lammas Would all be accepted as non profane. 我在indexOF()中添加了空格,因此诸如cathrine和dogsuit lammas之类的词都将被视为非亵渎。 The only problem i see is if the user starts the line with cat/dog/llama. 我看到的唯一问题是用户是否以cat / dog / llama开始生产线。 CAT! 猫! Would show up as non profane because there is no space at the start and there is no space afterwards, is there a String command to spread things out or am i completely on the wrong path? 会以亵渎的形式出现,因为开始时没有空间,事后也没有空间,是否有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");
}
}
Regex to the rescue! 正则表达式可以解救!
if (s1.matches("^.*\\b(cat|dog|llama)\\b.*$"))
Some explanation: 一些解释:
\\b
means word boundary \\b
表示单词边界 (a|b|c)
means "a or b or c" (a|b|c)
表示“ a或b或c” You could construct this from an array: 您可以从一个数组构造它:
String[] badWords = {"cat", "dog", "llama"};
String regex = "^.*\\b(" +
Arrays.toString(badWords).replace(", ", "|").replace("[", "").replace("]", "") +
")\\b.*$";
看一下Pattern
类和\\b
,这意味着单词边界。
您应该使用正则表达式 。
You could do as follows that way it will work for "cat" and "horse, cat, and goat" as well. 您可以按照以下方式进行操作,使其同样适用于“猫”和“马,猫和山羊”。
if(Regex.IsMatch(s1, @"\b(?:cat|dog|llama)\b", RegexOptions.IgnoreCase))
System.out.println("Profanity is in your Billboard");
Okay, I thought it was C#, but something similar exists in Java. 好的,我以为是C#,但是Java中也存在类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.