Java 获取一个字符串中,另一个字符串出现的次数

2023-07-29,,

Java 获取一个字符串中,另一个字符串出现的次数

思想:

1. indexOf到字符串中到第一次出现的索引
2. 找到的索引+被找字符串长度,截取字符串
3. 计数器++

代码实现:

 public class Test {
public static void main(String[] args) {
String str="helloword";
fun(str,"hello");
}
public static void fun(String str,String m){
//m代表字符的长度
int count=0;
while(str.indexOf(m)>=0){
int index=str.indexOf(m)+m.length();//获取每次找到之后的下标位置
str=str.substring(index);
count++;
}
System.out.println("指定字符串在原字符中出現:"+count+"次");
}
}

总结:最开始就是不明白为什么需要加上字符串的长度

Java 获取一个字符串中,另一个字符串出现的次数的相关教程结束。

《Java 获取一个字符串中,另一个字符串出现的次数.doc》

下载本文的Word格式文档,以方便收藏与打印。