【JAVA习题三十五】计算字符串中子串出现的次数


package erase;
public class 第四十九题计算子串出现的次数 {
    public static void main(String[] args) {
        String n = "balabal.. I LOVE YOU, I LOVE YOU, hahh... I LOVE YOU, I LOVE YOU, I LOVE YOU bbll";
        String m = "I LOVE YOU";
        int idex = 0; //遍历字符串
        int count = 0; //统计次数
        for(; idex < n.length(); ) {
            if(n.indexOf(m,idex) != n.lastIndexOf(m)) {//如果开头找到的子串和结尾找到的子串位置不一样,则计数器count+1
                idex += n.indexOf(m,idex);
                count++;
            }
        }
        count++;
        System.out.println("子串重复出现了"+count+"次");
    }
}

 index of和last index of都是索引文件。indexOf是查找元素第一次出现的位置的索引;lastIndexOf是查找元素最后一次出现的位置。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM