/*
* 2.一个子串在整个串中出现的次数
* "nbaernbatynbauinaopnsijkhgvnxbacnbadknba"
*
* 思路:
* 1,要找的子串是否存在,如果存在,获取所在位置,用indexof()完成
* 2,如果找到,那么就记录出现的位置,并在剩余的字符串中继续查找子串
* 而剩下字符串的起始位置是出现位置+子串长度
* 3,由此类推,通过循环完成查找,如果找不到就是-1,并对没错找到用计数器记录
*/
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class StringTest_1 { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 String str="nbaernbatynbauinaopnsijkhgvnxbacnbadknba"; 8 String key="nba"; 9 10 int count=getKeyStringCount1(str,key); 11 System.out.print("count="+count); 12 13 } 14 15 16 public static int getKeyStringCount1(String str, String key) { 17 int count=0; 18 int index=0; 19 while((index=str.indexOf(key,index))!=-1){ 20 index=index+key.length(); 21 count++; 22 } 23 return count; 24 } 25 26 27 /** 28 * 获取子串在整串中出现的次数 29 * @param str 30 * @param key 31 * @return 32 */ 33 public static int getKeyStringCount(String str, String key) { 34 //定义计数器 35 int count=0; 36 //定义变量记录key出现的位置 37 int index=0; 38 while((index=str.indexOf(key))!=-1){ 39 str=str.substring(index+key.length()); 40 count++; 41 } 42 return count; 43 } 44 }