java中,编写一个程序让用户分别输入字符串和子字符串,输出子字符串出现的次数。编写一个程序让用户分别输入字符串和子字符串,输出子字符串出现的次数。
时间: 2024-04-30 18:23:28 浏览: 83
下面是Java代码实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入字符串:");
String str = scanner.nextLine();
System.out.print("请输入子字符串:");
String subStr = scanner.nextLine();
int count = 0;
int index = str.indexOf(subStr);
while (index != -1) {
count++;
index = str.indexOf(subStr, index + 1);
}
System.out.println("子字符串出现的次数为:" + count);
}
}
```
运行程序,依次输入字符串和子字符串,即可得到子字符串出现的次数。例如,输入字符串为"hello world, hello java",子字符串为"hello",则输出结果为"子字符串出现的次数为:2"。
阅读全文
相关推荐











