Java:查找一个单词在字符串中出现的次数(是否有类似于 C# 的表达式)? [英] Java: Find the number of times a word is present in a String (is there something similar to expression of C#)?
问题描述
我对查找某个单词在字符串中出现的次数很感兴趣.
我看过SUN的例子Matcher Demo 使用匹配器(构造一个正则表达式并计算组数).
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 在 C# 中(来自 SO 问题).
Regex.Matches( input, "true" ).Count in C# (from SO question).
或者在我的上下文中:
如果我在循环中使用 contains
来检查 List
中的某些单词是否出现在 String
中是否有一个简单/优雅的如何获得(当场??)这个词出现的次数(我已经知道它存在)?
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)?
推荐答案
你可以这样做
Pattern p = Pattern.compile(toFind, Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
int occurances = p.split(text, -1).length -1;
这篇关于Java:查找一个单词在字符串中出现的次数(是否有类似于 C# 的表达式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!