用Java键盘收两个字符串,统计第二个字符串在第一个字符串里出现的次数
时间: 2023-11-17 22:05:03 浏览: 43
以下是用Java实现统计第二个字符串在第一个字符串里出现的次数的代码:
```java
import java.util.Scanner;
public class CountSubstring {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String str1 = scanner.nextLine();
System.out.print("请输入第二个字符串:");
String str2 = scanner.nextLine();
int count = 0;
int index = str1.indexOf(str2); // 查找第一个匹配的位置
while (index != -1) {
count++; // 匹配次数加1
index = str1.indexOf(str2, index + 1); // 从上一个匹配位置的下一个位置开始继续查找
}
System.out.println("第二个字符串在第一个字符串里出现的次数是:" + count);
}
}
```
运行程序后,输入第一个字符串和第二个字符串即可得到统计结果。其中,使用了String类的indexOf方法来查找第二个字符串在第一个字符串中的匹配位置,如果找到则计数器加1,然后从上一个匹配位置的下一个位置开始继续查找,直到找不到为止。最后输出统计结果。