如何在Java中过滤单词?

时间:2012-10-13 01:45:33

标签: java

我想检查在某些情况下是否存在“坏”字样,例如以寄存器形式检查ID。但是我不知道如何检查它。底部的代码就是我用它来做的。

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;
}

单词的模式用逗号分隔,我真的需要帮助!

3 个答案:

答案 0 :(得分:4)

最简单的方法是在排序数组中搜索一个单词,如下所示:

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

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

答案 1 :(得分:1)

另一个例子,如果你想在输入中寻找一组单词

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;
    }
}

但是,只有当你的输入只包含一个单词时,才能查找单词。(在这种情况下,数组中的顺序无关紧要。

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);
    }   
}

答案 2 :(得分:0)

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));
        
        
    }
    
}