Java 获取一个字符串中,另一个字符串出现的次数
思想:
1. indexOf到字符串中到第一次出现的索引
2. 找到的索引+被找字符串长度,截取字符串
3. 计数器++
代码实现:
1 public class Test { 2 public static void main(String[] args) { 3 String str="helloword"; 4 fun(str,"hello"); 5 } 6 public static void fun(String str,String m){ 7 //m代表字符的长度 8 int count=0; 9 while(str.indexOf(m)>=0){ 10 int index=str.indexOf(m)+m.length();//获取每次找到之后的下标位置 11 str=str.substring(index); 12 count++; 13 } 14 System.out.println("指定字符串在原字符中出現:"+count+"次"); 15 } 16 }
总结:最开始就是不明白为什么需要加上字符串的长度