public class Test1 {
// * 统计大串中小串出现的次数
// 大串:haohaoxuexi,tiantianxiangshang
// 小串:an
public static void main(String[] args) {
countTest1();
String s1 = "haohaoxuexi,tiantianxiangshang"; //定义大串
String s2 = "an"; //定义小串
int count = 0;
int index = 0;
while ((index = s1.indexOf(s2)) != -1) {
count++;
s1 = s1.substring(index + s2.length());
}
System.out.println("count=:"+count);
}
private static void countTest1() {
String s1 = "haohaoxuexi,tiantianxiangshang"; //定义大串
String s2 = "an"; //定义小串
int count = 0; //定义计数器
for (int i = 0; i < s1.length(); i++) { //遍历大串
if (s1.indexOf(s2) > 0) {
count++;
s1 = s1.substring(s1.indexOf(s2) + s2.length());
}
}
System.out.println("count=:"+count);
}
}
|
|