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是查找元素最后一次出現的位置。
