- 使用
indexOf(String str, int fromIndex)方法:
public class Demo {
public static void main(String[] args) {
String str = "HelloHello HelloHello World Hello China Hello Tomorrow";
// 匹配的子串在字符串中的下标
int index = 0;
// 计算出现的次数
int count = 0;
String findStr = "Hello";
while((index = str.indexOf(findStr, index)) != -1) {
System.out.print(str.charAt(index) + " ");
index += findStr.length();
count++;
}
System.out.println(count);
}
}// out: H H H H H H 6
本文介绍了一种使用Java的indexOf方法来查找并计数指定子字符串在目标字符串中出现次数的方法。通过一个示例程序展示了如何实现这一功能,并输出了匹配字符及出现次数。

539

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



