Java: Find the number of times a word is present in a String (is there something similar to expression of C#)?

北慕城南 提交于 2019-12-24 08:33:48

问题


I am interesting in finding the number of times a word appears in a String.
I have seen the example of SUN Matcher Demo using the matcher (constructs a regex and counts the groups).

I was interested if this is the only way or there is something else like e.g.

Regex.Matches( input, "true" ).Count in C# (from SO question).

Or in my context:

If I am in a loop using contains to check if certain words in the List appear in the String is there a simple/elegant way to get (on the spot??) the number of times the word occurs (that I already know it exists)?


回答1:


You can do something like

Pattern p = Pattern.compile(toFind, Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
int occurances = p.split(text, -1).length -1;


来源:https://stackoverflow.com/questions/8975019/java-find-the-number-of-times-a-word-is-present-in-a-string-is-there-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!