2

I am trying to create a profanity test for my app, but it seems to malfunction!! why?

code:

public boolean filter(String message)
{

    String[] words={*CUSS WORDS*};

    for(int i=0; i< (words.length-1); i++ )
    {
        if(message.indexOf(words[i].toLowerCase())!= -1)
        {
            return true;
        }
    }
    return false;
}

OR Another code (BUT SAME FUNCTION):

public boolean filter(String message)
{

    String[] words={CUSS WORDS};

    for(int i=0; i< (words.length-1); i++ )
    {
        if(message.contains(words[i}))
        {
            return true;
        }
    }
    return false;
}

So the PROBLEM IS: I tried these 2 pieces of codes with similar results. For example for "Fuck", if I enter "fu" into my app it stops it from being entered or for "ass", if I enter "as" it stop it from being entered! (Filter works to stop any profanity from entering the chat)

2 Answers2

1

Store your curse words in a set, then break up the users sentence into individual words. Check each word to see if it's in your set of curse words.

public boolean curse(String str){
    //Create your set here
   HashSet<String> wordSet = new HashSet<String>();

    //Use it's add function to add your curse words
    wordSet.add("ass");

    String array[] = str.split(" ");

    for(String s : array){
        if(wordSet.contains(s.toLowerCase()))
            return true;
    }

    return false;
 }
Elroy Jetson
  • 938
  • 11
  • 27
  • I was wondering how would I make the map of the curse words (Would it be possible for you to also give me an example) please if you dont mind. Thank You – Sriharsha Singam Dec 01 '16 at 02:51
  • 1
    why a map? maybe a List or a Set – Scary Wombat Dec 01 '16 at 02:58
  • @Elroy Jetson It did not work!!!! I did this:String[] words={"",",etc"}; List stringList = new ArrayList(Arrays.asList(words)); //HashSet set = new HashSet(Arrays.asList(words)); String array[] = message.split(" "); for(String s : array){ if(stringList.contains(s)) return true; } return false; The string array has so many curse words! – Sriharsha Singam Dec 01 '16 at 04:03
  • Thank You Guys Your Code Really Helped and Now It Works! Thank You So Much – Sriharsha Singam Dec 01 '16 at 12:09
1

I can't comment because of my reputation, but, continuing Elroy Jetson's answer, you initialize the HashSet using Arrays.asList, as is described here in this answer: https://stackoverflow.com/a/16194967/2836264. The HashMap constructor takes in this case a List<String>, that is created from the String[].

String[] cussArray = {"fuck", "shit", "brocolli"};
HashSet<String> cussSet = new HashSet<>(Arrays.asList(cussArray));
Community
  • 1
  • 1
reischapa
  • 41
  • 1
  • 5