问题描述
所以基本上我创建了一个代码来导入一个包含单词的文本文件,当我在代码中输入一个单词时,程序会查找该单词是否在我导入的文本文件中。
我最终想做的是找到索引号(在找到的行内)和找到单词的行号。通过执行
,我可以将代码打印出总文本中的索引号,但不在找到的行内String indexnum = s1;
System.out.println("Matches at index : " + indexnum.lastIndexOf(s2));
打印出类似的东西
'匹配索引:2949232'
我希望它打印的内容类似于...
'在第 4441 行的索引 26 处匹配'
我怎么能有任何想法......老实说,我的想法已经用完了。
解决方法
您在使用 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;
}