搜索一个短语的行

时间:2018-01-21 17:21:05

标签: string search

我正在尝试编写一个grep方法来搜索带有提供的用户输入字的文本文件。然后代码将搜索文本文件的每一行,搜索用户输入字。如果找到,将显示包含在<>所包围的正确位置的单词的行符号。

如果我使用这篇文章的第一行作为例子,如果是 -

用户输入:“a”

输出: 第1行:我正在尝试编程< a> grep方法搜索< a>文本文件< a>提供用户输入字。代码将

我已经写了大部分内容,但需要考虑包含的短语和同一行中的多个短语,例如在我的例子中。该方法应该是什么?

public static void grep(String[] phrases, Scanner words3) {
Scanner in = new Scanner(System.in);

    int line = 1;
    boolean found = false;
    String grep;

    System.out.print("\n\n\nPLease enter something to grep: ");
    grep = in.nextLine();
    System.out.print("\n");

    while(words3.hasNext() == true) { //check file for remaining lines of text and searches each for user input string
        String currentLine = words3.nextLine();

        if(currentLine.indexOf(grep) == -1) { //change so it accounts for the grep as a wrapped phrase and for multiple matches in the same line
            line++;
            continue;
        }
        else {

            System.out.print("Line " + line + " ");               
            int l = 0;

            while(l < currentLine.length()) {
                if(l == currentLine.indexOf(grep)) {
                    System.out.print("<" + grep + ">" ); 
                    l += grep.length() - 1;
                }
                else {
                    System.out.print(currentLine.charAt(l));
                }
                l++;
            }

            System.out.print("\n");
            line++;
            found = true;

        }
    }

    if(found == false) {
        System.out.print("[The word <" + grep + "> was not found]\n");
    }


}

0 个答案:

没有答案