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. The only problem i see is if the user starts the line with 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?
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.i开发者_如何学CndexOf(" 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(a|b|c)
means "a or b or c"
You could construct this from an array:
String[] badWords = {"cat", "dog", "llama"};
String regex = "^.*\\b(" +
Arrays.toString(badWords).replace(", ", "|").replace("[", "").replace("]", "") +
")\\b.*$";
Take a look at the Pattern
class, and \b
, which means word boundary.
You should use regular expressions.
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.
精彩评论