/*
统计大串中小串出现的次数
例如:"yuhellortyuhellosad"中"hello"出现了两次
*/
/*
分析:
1.使用String类中的indexOf(String str)方法,返回小串在大串中第一次出现的索引
2.使用substring(int beginIndex)方法,获得减去小串之前的所有字符串后的新字符串(小串出现的第一次索引+小串的长度)
*/
public class StringTest {
public static void main(String[] args) {
String s1 = "nojavaqwejavaqwewqjavaoiu";
String s2 = "java";
int count = 0; //定义变量统计s2在s1中出现的次数
int index; //定义变量获得S2出现时的索引
//确定s2的索引存在
while((index=s1.indexOf(s2))!=-1) {
count++;
s1= s1.substring(index + s2.length());
//获得每次s2出现后的字符串变化
System.out.println(s1);
}
System.out.println("java在字符串中出现了: "+count+" 次");
}
}