用java 写一个程序,实现在字符串”Java is my friend“ 中查找字母a的出现次数
时间: 2023-05-11 16:03:48 浏览: 61
可以使用以下代码实现:
```java
public class CountA {
public static void main(String[] args) {
String str = "Java is my friend";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'A') {
count++;
}
}
System.out.println("字母a出现的次数为:" + count);
}
}
```
输出结果为:
```
字母a出现的次数为:2
```
相关问题
用java写一个程序 获得一个字符串再另一个字符串出现的次数
以下是一个用Java编写的程序,用于获取一个字符串在另一个字符串中出现的次数:
```java
import java.util.Scanner;
public class StringOccurrence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the main string: ");
String mainString = scanner.nextLine();
System.out.print("Enter the sub string: ");
String subString = scanner.nextLine();
int count = 0;
int index = mainString.indexOf(subString);
while(index != -1) {
count++;
index = mainString.indexOf(subString, index + subString.length());
}
System.out.println("The sub string \"" + subString + "\" occurs " + count + " times in the main string.");
}
}
```
该程序要求用户输入两个字符串,然后使用`indexOf()`方法在主字符串中查找子字符串。如果它找到子字符串,则计数器增加并继续查找。循环结束后,程序将打印子字符串在主字符串中出现的次数。
用java写,给出一个字符串统计字母n出现的次数
以下是Java代码实现:
```java
public class CountLetterN {
public static void main(String[] args) {
String str = "New York is a beautiful city";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'n' || str.charAt(i) == 'N') {
count++;
}
}
System.out.println("The letter 'n' appears " + count + " times.");
}
}
```
解释:
1. 定义一个字符串 `str`,并赋值为 "New York is a beautiful city"。
2. 定义一个计数器变量 `count`,初始化为 0。
3. 使用 for 循环遍历字符串的每个字符。
4. 在循环中,判断当前字符是否为字母 n 或 N,如果是,则将计数器加 1。
5. 循环结束后,输出字母 n 出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)