查找给定查询中的所有可能单词

时间:2015-06-08 21:50:05

标签: java

我想创建一个单词搜索java程序,每当我输入一个包含通配符的单词时,例如:b * t

我想从我拥有的文本文件中找到适合该单词的所有可能单词。

这是我到目前为止所做的,

    Scanner cin = new Scanner(System.in);
    System.out.print("Enter a query: ");
    String input = cin.nextLine();

    try{
        String line;
        BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
        while((line = br.readLine()) != null){
            if (input.length()==line.length()) {//show all letters in that range
               if ('*' != input.charAt(x)) {//check if letters contain '*'
                    if (line.charAt(x) == input.charAt(x)) {//check if letters match
                    System.out.print(line+"\n");//show all words that fit criteria
                }else{//skip letter
                   x=+1;
               }
                }else{//skip
                   x=+1;
               }
            }// end if
        }// end while

    }catch (IOException e){
        e.printStackTrace();
    }

我可以找到一定长度的所有单词,我只是在努力寻找适合我查询的单词。

1 个答案:

答案 0 :(得分:0)

我相信这符合您的需求:

public static void main(String [] args){

    Scanner cin = new Scanner(System.in);
    System.out.print("Enter a query: ");
    String input = cin.nextLine();
    try{
        String line;
        BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
        while((line = br.readLine()) != null){
            String[] words = line.split(" ");
            for(String w: words) {
                String p = "^" + input.replaceAll("\\*", ".*") + "$";
                if (w.matches(p)) {
                    System.out.println(w);
                }
            }
        }

    }catch (IOException e){
        e.printStackTrace();
    }

    System.exit(0);
}
相关问题