gpt4 book ai didi

Java:搜索多次出现的文本

转载 作者:行者123 更新时间:2023-11-30 08:51:13 24 4
gpt4 key购买 nike

问:如果给我一个非常大的随机英文单词,并让我找到被空格分割的特定子字符串 [例如,“how now”、“brown cow”等],然后返回它出现的位置,我该怎么做?

答:我有一个部分解决方案,但我请求 Stack Overflow 社区帮助完成最后一点。

程序应该如何运行:

  • 给程序一个文本文件
  • 搜索整个文件
  • 返回行号和字号;字数与行有关

  • 如果找到“how now”作为连续两行的前两个词,它将返回在第 k 行位置 1 找到的“how now”,并在第 k+1 行位置 1 再次找到

  • 如果该行是“how now the count of monte brown cow cristo”,那么它应该能够将“how now”和“brown cow”检测为两个单独的事件。

解决方案一:

int chn = 0;
int cbc = 0;

Scanner in = new Scanner(new File("filename.txt"));
String temp = in.nextLine();

Pattern phn = Pattern.compile("how now");
Pattern pbc = Pattern.compile("brown cow");
Matcher mhn = null;
Matcher mbc = null;

while (in.hasNext()) {

mhn = phn.matcher(temp);
while (mhn.find()) m++;

mbc = pbc.matcher(temp);
while (mbc.find()) j++;

temp = in.nextLine();
} // Formatted output comes after

问题是虽然这通过使用模式和匹配器跟踪出现次数 (chn, cbc) 并且还跟踪按时间顺序发生的事件,并且是这样做最快的算法,但我不知道如何我可以跟踪它在行中出现的位置。

解决方案 2:

Scanner in = new Scanner(new File("filename.txt"));
ArrayList<String> wordsInLine = new ArrayList<>();
String temp = in.nextLine();
String temp2 = "";

ctL = 1;

while (in.hasNext()) {
if (temp.contains("how now")) {
for (String word : temp.split(" ")) {
wordsInLine.add(word);
}
for (int i = 0; i < wordsInLine.size(); i++) {
if (wordsInLine.get(i).equals("how") ||
wordsInLine.get(i + 1).equals("now")) {

System.out.println("This returns line count and "
+ "the occurrence by getting i");
}
}
}

ctL++;
temp = in.nextLine();
}

但是第二个部分解决方案似乎非常低效且非常慢,对包含“现在如何”的每一行都使用两个 for 循环。
有更优雅的方法吗?

最佳答案

解决方案 1 的效率肯定高得多,我肯定会采用该方法。

为了跟踪特定行中匹配模式的位置,您可以使用 start()end() Matcher 的方法类获取相应的索引。

关于Java:搜索多次出现的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com