Checking if a string contains another string twice

Discussion in 'Plugin Development' started by InfamousSheep, Jul 10, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    InfamousSheep

    So I'm currently trying to filter out bad words in a player's message. However, when I loop through I'm adding 1 to a value to check if X amount of bad words is reached then it cancels the message completely. Only problem is, if they repeat the same bad word twice, it doesn't add an extra point.
    Code:
    List <String> phrases = Main.BannedPhrases;
    int words = 0;
    for (String censored : phrases) {
    if (event.getMessage().toLowerCase().contains(censored.toLowerCase())) {
    event.setMessage(event.getMessage().replaceAll(censored, "***"));
    words += 1;
    }
    }
     
    if(words >= 2) {
    event.setCancelled(true);
    player.sendMessage("§cThat's way to many bad words!"); // ADD WARNING
    } else if(words >= 1 && words < 2) {
    player.sendMessage("§cWatch your language!"); // ADD WARNING
    }
    
    Any help is appreciated, thanks in advance.
     
  2. Offline

    Wizehh

    First, "convert" the String (e.getMessage()) to a String array by using String.split(" "). Then, loop over each word in the new array, and increment your variable like you did before.
     
  3. Offline

    InfamousSheep

    Thanks dude, seems to be working now.

    Code:
    List <String> phrases = Main.BannedPhrases;
    int badwords = 0;
    String[] splited = message.split(" ");
    for(String wordz : splited) {
    for (String censored : phrases) {
    if (wordz.toLowerCase().contains(censored.toLowerCase())) {
    event.setMessage(event.getMessage().replaceAll(censored, "***"));
    badwords += 1;
    }
    }
    }
     
    player.sendMessage("" + badwords);
     
    if(badwords >= 2) {
    event.setCancelled(true);
    player.sendMessage("§cThat's too many bad words!"); // ADD WARNING
    } else if(badwords >= 1 && badwords < 2) {
    player.sendMessage("§cWatch your language!"); // ADD WARNING
    }
    
    Not sure if this is as efficient as possible but none the less it seems to be working fine...

    I've found a problem with this, if the censored word contains a space, it's not censored. Is there fix for this?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 9, 2016
  4. Offline

    Derpiee

    If you want to eliminate cuss words effectively you want to look into Regex :)
     
Thread Status:
Not open for further replies.

Share This Page