在字符串a(長串)中查找字符串b(短串)出現的次數
package doudou; public class test_indexOf_0810 { public static void main(String[] args) { String a = "aaaaabcbcbvbbbbbvbvbvbbvvvcbcbcbc"; String b = "bc"; demo_01(a, b); demo_02(a, b); } // 方法一 public static void demo_01(String a, String b) { // 1.原始長度 int a_length = a.length(); // 2.替換的長度 int b_length = b.length(); // 3.查找 int c = a.replaceAll("bc", "").length(); // 4/相減 System.out.println((a_length - c) / b_length); } // 方法二 public static void demo_02(String a, String b) { int count = 0; //返回指定字符b在字符串a中第一次出現的起始索引,如果a字符串中沒有這樣的字符,則返回 -1。 while (a.indexOf(b) != -1) { count++; //將截取后的字符串重新賦值給a(之前沒重新賦值,就死循環了) a = a.substring(a.indexOf(b) + b.length(), a.length()); } System.out.println(count); } }