统计子串在另一个字符中出现的次数

package cc;

//要求:统计一个子串在一个字符串中出现的次数
//思路:不断地截取子串
public class StringTest1 {
    public static void main(String[] args) {
        StringDemo1 demo1 = new StringDemo1();
        System.out.println("出现的次数是" + demo1.count("abcabcccabc", "abc"));
    }
}

class StringDemo1 {
    public int count(String string, String subString) {
        int count = 0;
        while (string.indexOf(subString) != -1) {// 只要子串在原串中出现
            count++;
            int local = string.indexOf(subString);
            string = string.substring(local + 1);// 注意是local+1
        }
        return count;
    }
}

转:http://blog.csdn.net/lfdfhl/article/details/8195110

posted @ 2013-06-24 14:05  还是你最好  阅读(713)  评论(1编辑  收藏  举报