package yu;
public class Main {
public static void main(String[] args) {
String str="YUgdagdgagdgaYUdgygsYUgsdgfiookf";//整串
String key="YU";//子串
int count =getKeyNum(str ,key);
System.out.println("count="+count);//打印结果count=3
}
public static int getKeyNum(String str,String key) {
int count =0;//记录次数
//如果整串都不包含,返回0
if (!str.contains(key)) {
return count;
}
//定义变量记录key出现的位置
int index=0;
while((index=str.indexOf(key))!=-1) {//返回子串的位置
str=str.substring(index+key.length());//从下一个位置开始
count++;
}
return count;
}
}
public class Main {
public static void main(String[] args) {
String str="YUgdagdgagdgaYUdgygsYUgsdgfiookf";//整串
String key="YU";//子串
int count =getKeyNum(str ,key);
System.out.println("count="+count);//打印结果count=3
}
public static int getKeyNum(String str,String key) {
int count =0;//记录次数
//如果整串都不包含,返回0
if (!str.contains(key)) {
return count;
}
//定义变量记录key出现的位置
int index=0;
while((index=str.indexOf(key))!=-1) {//返回子串的位置
str=str.substring(index+key.length());//从下一个位置开始
count++;
}
return count;
}
}