How to check if string list contains an exact string?

What I’m trying to do is make an Anti-swear plugin for my server. It works fine, but players can bypass it easly. Let’s say that in my config i have the word "test" listed. If the player types the word "test" in the chat normally, the plugin will detect it. But if the player types in, for example "testtttttttt" the the plugin will not detect it. How can I make it so that it detects the word as long as its just there?
Here is the code I have currently:

public class EventsClass implements Listener {

        AntiSwear plugin = AntiSwear.getPlugin(AntiSwear.class);

        // Message when player joins the server
        @EventHandler
        public void onPlayerJoinEvent(PlayerJoinEvent event) {
            Player player = event.getPlayer();
            player.sendMessage(ChatColor.GOLD + "This server is running AntiSwear v1.0");

        // The punishment system
        }
        @EventHandler
        public void chatevent(AsyncPlayerChatEvent event) {
            for (String s : event.getMessage().split(" ")) {
                if (plugin.getConfig().getStringList("swears").contains(s)) {
                    event.setCancelled(true);
                    event.getPlayer().sendMessage(ChatColor.RED + "┬žlProfanity is not allowed on this server!");

                    // The punishment itself
                    Bukkit.getScheduler().runTask(plugin, () -> {

                        event.getPlayer().damage(10);
                        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "smite " + event.getPlayer().getName());
                        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "eco take " + event.getPlayer().getName() + " 100");
                        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "burn " + event.getPlayer().getName() + " 5");
                        plugin.getServer().broadcastMessage(ChatColor.GOLD + "┬žlPlayer " + event.getPlayer().getName() + " ┬žlused a swear word and has been punished!");
                    });
                }
            }
        }
    }

>Solution :

Instead of a contains check on the list which checks for exact matches, you’ll need to loop over the list and for each item do a contains check:

List<String> swears = plugin.getConfig().getStringList("swears")
  .stream()
  .map(swear -> swear.toLowerCase() )
  .collect(Collectors.toList());

for(String s : event.getMessage().split(" ")){
  if(swears.stream().anyMatch(swear -> s.toLowerCase().contains(swear)){
    event.setCancelled(true);
    //...
  }
}

Leave a Reply