Steve Gom
Steve Gom

Reputation: 75

How to filter words in Java?

I want to check if there are 'bad' words in some cases such as checking IDs in register form. But I do not know how to check it.. The bottom code is what I got far with it.

String words = "admin,administrator,babo,sir,melon";

public boolean checkWord(String input) {
   if(something here that i need to find??) return false;
   else return true;
}

The pattern of words are divided in comma, and I really need help with it please!

Upvotes: 2

Views: 6719

Answers (3)

itsME -_-
itsME -_-

Reputation: 1

public class steve {

    
    static boolean checkWord(String input, String words) {
        if(words.contains(input)) {
            return true;
        }
        else {
            return false;
        }
        
    }
    
    public static void main(String[] args) {
        
        String words = "admin,administrator,babo,sir,melon";
        
        System.out.print(steve.checkWord("babo",words));
        
        
    }
    
}

Upvotes: 0

PbxMan
PbxMan

Reputation: 7625

Another example if you want to look for group of words inside your input

public class TestCheckWord {
    static String words = "admin,administrator,babo,sir,melon";
    public static void main (String args[]){        
        System.out.println(checkWord("Hello melon"));
        System.out.println(checkWord("Hello sir"));
        System.out.println(checkWord("Hello you"));
    }
    public static boolean checkWord(String input) {
        String wordArray[] = words.split(",");
        for(int i=0; i<wordArray.length; i++){
            if(input.indexOf(wordArray[i])>-1)
                return true;            
        }
        return false;
    }
}

and yet even another way to look for words only if your input contains only one word.(the order in the array doesn't matter in this case.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TestCheckWord2 {
    public static void main (String args[]){        
        System.out.println(checkWord("babo"));
        System.out.println(checkWord("bobo"));      
    }
    private static String[] WORDS =  {"admin", "babo", "melon", "sir", "administrator"};
    private static Set<String> mySet = new HashSet<String>(Arrays.asList(WORDS));
    public static boolean checkWord(String input) { 
        return mySet.contains(input);
    }   
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

The simplest thing would be to search for a word in a sorted array, like this:

private static String[] WORDS = new String[] {
    "admin", "administrator", "babo", "melon", "sir"
};

public boolean checkWord(String input) {
    return Arrays.binarySearch(WORDS, input) < 0; // Not found
}

Upvotes: 5

Related Questions