编程:计算字符串中子串出现的次数的程序。
public class SubNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串:");
String str = sc.next();
System.out.println("输入子字符串:");
String substr = sc.next();
int count = 0; // 记录子字符串出现的个数
int index = 0; // 记录子字符串出现的位置
while (true) {
index = str.indexOf(substr, index);
if (index != -1) {
str = str.substring(index+substr.length());
count++;
index = 0;
} else {
break;
}
}
System.out.println(substr+"出现的次数为"+count);
}
}