我有一个看起来像的字符串:
"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!".
我想计算字符串中is
的次数。
我怎样才能用Java做到这一点?
答案 0 :(得分:30)
一种简单的方法是使用Apache StringUtils countMatches
StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");
答案 1 :(得分:10)
int index = input.indexOf("is");
int count = 0;
while (index != -1) {
count++;
input = input.substring(index + 1);
index = input.indexOf("is");
}
System.out.println("No of *is* in the input is : " + count);
答案 2 :(得分:4)
如果您更喜欢正则表达式,这是一个正则表达式解决方案:
String example = "Hello my is Joeseph. It is very nice to meet you. isWhat a wonderful day it is!";
Matcher m = Pattern.compile("\\bis\\b").matcher(example);
int matches = 0;
while(m.find())
matches++;
System.out.println(matches);
在这种情况下,“isWhat”中的“is”被忽略,因为模式中的\ b边界匹配器
答案 3 :(得分:2)
String haystack = "Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!";
haystack.toLowerCase();
String needle = "is";
int numNeedles = 0;
int pos = haystack.indexOf(needle);
while(pos >= 0 ){
pos = pos + 1;
numNeedles = numNeedles + 1;
pos = haystack.indexOf(needle,pos);
}
System.out.println("the num of " +needle+ "= " +numNeedles);
答案 4 :(得分:1)
这考虑了“替换”的长度
String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)
答案 5 :(得分:1)
拆分每个“”(空白)并用循环检查输出的字符串[]
答案 6 :(得分:1)
您可以找到code here。 奇怪的是,它看起来像是罗比的那个。