- /*
- *需求:获取一个字符串在另一个字符串中出现的次数
- *思路:1、从起始位置开始寻找子串
- * 2、若找到,从子串最后一个位置之后,继续寻找。每次找到,用一个计数器自增
- * 3、若找不到,则返回计数器
- */
- public class StringCount {
- /**
- * 在字符串string中统计指定子串strToCount出现的次数
- * @param string 需要统计的字符串
- * @param strToCount 被统计的子串
- * @return 子串计数
- */
- static int count(String string, String strToCount){
- int count = 0; //计数器
- int index = 0; //表示寻找范围的索引
-
- //若找到子串,则继续
- while((index = string.indexOf(strToCount, index)) != -1){
- index = index + strToCount.length(); //从找到位置的后一个位置开始继续寻找
- ++count;
- }
-
- return count;
- }
-
- public static void main(String[] args) {
- String str = "abc def abdef acd ab";
- System.out.println("string = " + str);
- System.out.println(count(str, "ab"));
- }
- }
复制代码
|
|