方法一:采用String类中indexOf()方法;
public class SubStringCount {
public static void main(String[] args) {
String str1 = "abcjavanbajavasrcjavammmjava";
String str2 = "java";
int count = 0;
int index=str1.indexOf(str2);
while(index!=-1){
index = str2.length() + index;
count++;
index = str1.indexOf(str2, index);
}
System.out.println(count);
}
}
方法二:采用String类中substring()方法;
public class SubStringCount {
public static void main(String[] args) {
String str1 = "abcjavanbajavasrcjavammmjava";
String str2 = "java";
int count = 0;
int index = 0;
while((index=str1.indexOf(str2))!=-1){
index = str2.length() + index;
count++;
str1 = str1.substring(index, str1.length());
}
System.out.println(count);
}
}
原文地址:https://www.cnblogs.com/xiaowenwen/p/10138631.html