我有一个看起来像这样的字符串:
"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!".
我想要计算字符串中出现is
的次数。
在Java中,我该如何做到这一点?
我有一个看起来像这样的字符串:
"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!".
我想要计算字符串中出现is
的次数。
在Java中,我该如何做到这一点?
一种简单的方法是使用Apache StringUtils中的countMatches
函数。
StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");
StringUtils
不是主要用于框架内部吗?也就是说,它可以工作,但在这方面Apache显然更好。 - Michael Piefelint 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);
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);
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);
char
类型的变量从何时开始能够容纳多个字符? - LuigiEdlCarno按每个空格进行分割,并使用循环检查输出的字符串数组
这考虑了“replace”长度的影响
String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)