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; } }