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;
}
}
本文提供了一个简单的Java程序示例,展示了如何在给定的字符串中查找特定子串出现的次数。通过使用基本的字符串操作方法,如indexOf和substring,该程序能够有效地计算并输出结果。
3348

被折叠的 条评论
为什么被折叠?



