java统计一个子串在指定字符串中出现的次数

今天查着用了用String类里的几个方法,分享下代码

题目要求:统计一个子串在指定字符串中出现的次数( 提示java字串出现了6次)

 1 public class SearchSameString {
 2 
 3     public static void main(String[] args) {
 4         // 定义俩个字符串
 5         String shortStr = "java";
 6         String longStr = "javasdfjavawerjavavsswetjavadfgdfgjavadfgdfbtujava";
 7         // 调用searchCount方法
 8         int count = searchCount(shortStr, longStr);
 9         // 输出字符串出现的次数
10         System.out.println("java出现的次数是:" + count);
11 
12     }
13 
14     // 定义searchCount方法,来返回字符串出现的个数
15     public static int searchCount(String shortStr, String longStr) {
16         // 定义一个count来存放字符串出现的次数
17         int count = 0;
18         // 调用String类的indexOf(String str)方法,返回第一个相同字符串出现的下标
19         while (longStr.indexOf(shortStr) != -1) {
20             // 如果存在相同字符串则次数加1
21             count++;
22             // 调用String类的substring(int beginIndex)方法,获得第一个相同字符出现后的字符串
23             longStr = longStr.substring(longStr.indexOf(shortStr)
24                     + shortStr.length());
25 
26         }
27         // 返回次数
28         return count;
29     }
30 
31 }

 

posted on 2015-01-24 20:38  红可可  阅读(11284)  评论(2编辑  收藏  举报

导航