当前位置: 动力学知识库 > 问答 > 编程问答 >

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!

网友答案:

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);
    }   
}
网友答案:

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
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: