在另一个字符串中查找某个字符串并计算它出现的次数

Look for a certain String inside another and count how many times it appears

我试图在文件内容中搜索一个字符串,我进入了一个字符串。

我已经尝试使用 PatternMatcher,它们适用于这种情况:

Pattern p = Pattern.compile("(</machine>)");
Matcher m = p.matcher(text);
while(m.find()) //if the text "(</machine>)" was found, enter
{
    Counter++;
}

return Counter;

然后,我尝试使用相同的代码来查找我有多少个标签:

Pattern tagsP = Pattern.compile("(</");
Matcher tagsM = tagsP.matcher(text);
while(tagsM.find()) //if the text "(</" was found, enter
{
    CounterTags++;
}

return CounterTags;

在这种情况下,return 值始终为 0。

尝试使用下面的代码,顺便说一句,不要使用 Pattern:-

String actualString = "hello hi how(</machine>) are you doing. Again hi (</machine>) friend (</machine>) hope you are (</machine>)doing good.";
//actualString which you get from file content
String toMatch = Pattern.quote("(</machine>)");// for coverting to regex literal
int count = actualString .split(toMatch, -1).length - 1; // split the actualString to array based on toMatch , so final match count should be -1 than array length.
System.out.println(count);

输出 :- 4

您可以使用 Apache commons-lang util 库,有一个函数 countMatches 完全适合您:

int count = StringUtils.countMatches(text, "substring");

而且这个函数是空安全的。 我建议您探索 Apache commons 库,它们提供了很多有用的常用实用程序方法。