您的位置:首页 > 其它

计算字符串中子串出现的次数

2018-04-06 20:55 288 查看
/**
 * 计算字符串中子串出现的次数
 *
 * @author Dreamweaver
 *
 */
public class Demo49 {

    public static void main(String[] args) {
        String str = "abcqwegdslabcsdlfjabcjsdo";
        // 定义一个子串
        String s = "abc";
        // 统计次数
        int count = 0;
        while (true) {
            // 返回第一次出现子串的索引
            int index = str.indexOf(s);
            if (index!= -1) {
                str = str.substring(index + s.length(), str.length()-1);
                count++;
            } else {
                break;
            }
        }
        System.out.println("子字符串一共在字符串中出现了" + count + "次");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: