【问题标题】:How do I search for a phrase in a string without looking for the word in the phrase multiple times如何在字符串中搜索短语而不多次在短语中查找单词
【发布时间】:2018-09-03 09:22:03
【问题描述】:

所以我想搜索用户输入的参数,例如“Hello there”,而不是寻找“Hello”和“There”本身。

String[] words = text.split("\\s+");        
    for (int i = 0; i < words.length; i++){
         if (searchString.contains(words[i])){
             counter++;
         }
    }

这里的代码我基本上试图计算一个字符串在 txt 文件中出现的次数。

【问题讨论】:

  • 嗯? “你好”是两个词。你为什么spliting 文本? text.contains(searchString)?您要计算searchStringtext 中出现的次数吗?
  • 你的文本文件是什么样子的?请显示示例输入和预期输出。
  • 是的,我想计算“Hello there”被放在一起的次数,而不是单独通过文本。我从空格中分离出来,是的,我想计算 searchString 出现了多少次。
  • 这是预期的输出(java TextSearch "drops of blood" input.txt) 输出:雪,她刺破了手指,从雪上掉下三滴血。当她看到它看起来多么明亮和红色时,她总共匹配:1

标签: java arrays string search


【解决方案1】:

我可能会使用 Pattern 和 Matcher。

  Pattern p = Pattern.compile("Hello there");
  Matcher m = p.matcher(text);
  int counter = 0;
  while (m.find()) {
      counter++;
      System.out.println("found hello there!");
  }

计数器将反映在文本中找到的匹配数。

(已编辑答案以反映 cmets 中的说明)

【讨论】:

  • 这个问题是我试图匹配 String[] 单词,它是一个数组而不是文本。我这样做是因为 String[] words 分割了文本文件的空格。
  • 你可以做 Arrays.toString(words) 然后执行匹配。为什么需要数组?
  • 所以我可以使用 text.split
【解决方案2】:

使用模式、匹配器和自增整数

public static int stringCounter(String input, String toSearch)
{
     int counter = 0;
     Pattern pattern = Pattern.compile(toSearch);
     Matcher  matcher = pattern.matcher(input);
     while (matcher.find()) counter++;
     return counter;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多