- /*
- * 需求:统计大字符串中小字符串出现的次数
- * woaijavawohenaijavawozhendehenaijavaxinbuxinwoaijava
- * 结果:java出现了4次
- * 分析:
- * A:定义一个统计变量,初始化值为0
- * B:先获取java在大字符串中第一次出现的索引
- * 如果索引值返回-1,说明大串中不存在java
- * 如果索引值返回的不是-1,说明大串中存在java,统计变量++
- * C:把刚才的索引值+小串的长度作为起始位置截取大串,作为新的大串
- * D:重复B操作
- * E:输出统计变量
- */
- public class StringTest4 {
- public static void main(String[] args) {
- String maxString = "woaijavawohenaijavawozhendehenaijavaxinbuxinwoaijava";
- String minString = "java";
- int count = getCount(maxString, minString);
- System.out.println(minString+"出现了"+count+"次");
-
-
- }
- public static int getCount(String maxString,String minString) {
- int count = 0;
- int index;
- while((index = maxString.indexOf(minString))!= -1) {
- count++;
- maxString = maxString.substring(index+minString.length());
- index = maxString.indexOf(minString);
-
- }
- return count;
- }
- }
复制代码
|
|