用JavatoString输入一个字符串,再输入一个字符,判断字符在该字符串中出现的次数。
时间: 2023-07-16 09:13:21 浏览: 69
下面是一个用Java实现的简单示例:
```java
import java.util.Scanner;
public class CharCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String str = sc.nextLine();
System.out.print("请输入一个字符:");
char ch = sc.next().charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("该字符在字符串中出现的次数为:" + count);
}
}
```
首先,我们通过 `Scanner` 类获取用户输入的字符串和字符。然后,我们使用一个 `for` 循环遍历字符串中的每个字符,并使用 `if` 语句判断是否与输入的字符相等。如果相等,则将计数器 `count` 加 1。最后,我们打印出计数器的值,即为该字符在字符串中出现的次数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)