1.indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
2.substring(x) 从第x个字符到最后;substring(x,y) 从第x个字符到第y个 字符截取
学习代码:
思路:indexOf能找到有没有,但不会计数,需要配合substring 截取子串
public class StringTest_2 {
public static void main(String[] args) {
String str = "BeautyLeaJonEEloveLealljoneeleakf";
String key = "Lea";
int count = getKeyStringCount(str, key);
System.out.println(count);
}
public static int getKeyStringCount(String str, String key) {
int count = 0;
int index = 0;
while ((index = str.indexOf(key)) != -1) {
str = str.substring(index + key.length());
count++;
}
return count;
}
}
运行结果:

题目来源:毕向东-15-10
本文介绍了一种使用Java实现的字符串匹配计数方法。通过`indexOf`方法查找子字符串出现的位置,并结合`substring`方法截取子串,从而计算出主字符串中特定子字符串出现的次数。
2180

被折叠的 条评论
为什么被折叠?



