打印出一行内的索引和找到单词的行号

j7dteeu8  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(323)

基本上,我创建了一个代码,导入一个包含单词的文本文件,当我在代码中输入一个单词时,程序会发现这个单词是否在我导入的文本文件中。
我最后想做的是找到索引号(在找到的行内)和找到单词的行号。通过执行以下操作,我可以将代码从总文本中打印出索引号,但不能在找到的行中打印

String indexnum = s1;
System.out.println("Matches at index : " + indexnum.lastIndexOf(s2));

上面印的是
'索引处的匹配:2949232'
我希望它打印的内容类似于。。。
'在第4441行的索引26处匹配'
你知道我该怎么做吗。。老实说,我已经没有主意了。

t3irkdon

t3irkdon1#

你在用什么 Files.readString() ? 我建议使用扫描仪或类似设备逐行扫描:

Scanner in = new Scanner(new File(filepath)); // be sure to catch or throw the exception
for (int lineNum = 1; in.hasNextLine(); lineNum++) {
    String line = in.nextLine();
    int index = line.indexOf(s2);
    if (index >= 0) {
        System.out.println("Match found on line " + lineNum + ", column " + (index + 1));
    }
}

但是,如果您需要将其存储为一大块文本,也许您可以利用这个版本的indexof,它为搜索提供一个起始索引。

for (int startIndex = 0, endIndex = 0, lineNum = 1; true; lineNum++) {

    endIndex = s1.indexOf("\n", startIndex);
    String line;
    if (endIndex < 0) {
        // No newline found. Continue to the end of the string.
        line = s1.substring(startIndex);
    } else {
        line = s1.substring(startIndex, endIndex);
    }

    int matchIndex = line.indexOf(s2);
    if (matchIndex >= 0) {
        System.out.println("Match found on line " + lineNum + ", column " + (matchIndex + 1));
    }

    if (endIndex < 0) {
        break;
    }

    startIndex = endIndex + 1;
}

相关问题