搜索词的输出行数

时间:2017-11-25 06:19:48

标签: java regex

我正在编写一个程序来输出文本文件中搜索词的行号。非常感谢任何帮助。

    while (index >= 0) {
        index = fileText.indexOf(searchWord, index + 1);
        indexOfSearch.add(index);
    }
    System.out.println(fileText);//print the text from file
    for (int j = 0; j < indexOfSearch.size() - 1; j++) {//each index of search word
        String spaces = "";//spaces to caret
        int indexTo = 0;//how many spaces will be added
        if(j < 1){
        indexTo = indexOfSearch.get(j);//the first index
        }else{            
            indexTo = (indexOfSearch.get(j) - indexOfSearch.get(j - 1) - 1);//all other indexes in the row
        }            
        for (int i = 0; i < indexTo; i++) {//add appropriate number of spaces to word  
            spaces += " ";//add a space
        }
        System.out.print(spaces + "^");//print the spaces and spaces
    }
    System.out.println("");//used to make the print slightly easier to look at.
}

}

2 个答案:

答案 0 :(得分:1)

希望这能帮到你。我建立了一个课程,你可以为你读的每一行打电话。

这可以很容易地插入到您当前的代码中。如果你需要帮助整合它,我非常乐意提供帮助。

我在评论中几乎一步一步地将其分解。

public class FindWord {

    public static void main(String[] args) {

        FindWord f = new FindWord();

        f.findWords("As you can test, we can put as many test in test as we test", "test");
    }


    public void findWords(String str, String search) {//This can easily be added into your project

        String fileText = str;//text from file
        String searchWord = search;//the word being searched
        List<Integer> indexOfSearch = new ArrayList<>();
        int index = fileText.indexOf(searchWord);
        indexOfSearch.add(index);
        while (index >= 0) {
            index = fileText.indexOf(searchWord, index + 1);
            indexOfSearch.add(index);
        }
        System.out.println(fileText);//print the text from file
        for (int j = 0; j < indexOfSearch.size() - 1; j++) {//each index of search word
            String spaces = "";//spaces to caret
            int indexTo = 0;//how many spaces will be added
            if(j < 1){
            indexTo = indexOfSearch.get(j);//the first index
            }else{            
                indexTo = (indexOfSearch.get(j) - indexOfSearch.get(j - 1) - 1);//all other indexes in the row
            }            
            for (int i = 0; i < indexTo; i++) {//add appropriate number of spaces to word  
                spaces += " ";//add a space
            }
            System.out.print(spaces + "^");//print the spaces and spaces
        }
        System.out.println("");//used to make the print slightly easier to look at.
    }

}

我创建了一个包含多个正在搜索的单词的字符串,以显示它是如何工作的。

如果我错过了一项要求,请告诉我,我会相应修理。

我希望这有帮助!

编辑:我将所有内容放在一起并包含更新的要求整个来源可以在这里找到:

SO_AustinProject

答案 1 :(得分:0)

这里的问题是,只有固定宽度的字体才能通过计算字符来预测某些内容的位置。大多数字体都是变量&#39;。所以&#39; lllll&#39;比'0000&#39;更窄例如。所以基本上如果你可以控制字体并以Courier为例(google&#39;固定宽度字体&#39;)你将能够使用空格来定位插入符号,但除了固定字体之外它基本上是基本的不可能这样做