获取itcast字符串在整个字符串中出现的次数 "gzitcastabcgzabcitcastabcjavaabcandroiditcast"
public class TestReadStringItcast { public static void main(String[] args) { String a = "gzitcastabcgzabcitcastabcjavaabcandroiditcast"; String b = "itcast"; System.out.println(getSubNum(a, b)); }
public static int getSubNum(String a, String b) { int num = 0; String str = a; int index = a.indexOf(b); while (index != -1) { num++; str = str.substring(index + b.length() - 1); index = str.indexOf(b); } return num; } } 输出:出现次数:3 |