Java定义一个方法,接收一个字符串和一个字符,统计该字符在字符串中出现的次数。
时间: 2024-05-16 17:12:22 浏览: 6
可以使用以下代码实现:
```
public static int countChar(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
```
这个方法接收一个字符串和一个字符作为参数,使用一个计数器变量来记录字符在字符串中出现的次数。然后使用一个 for 循环遍历字符串中的每个字符,如果当前字符与传入的字符相同,就将计数器加 1。最后返回计数器的值即可。
相关问题
java定义一个方法,接收一个字符串和一个字符,统计该字符在字符串中出现的次数
可以定义一个方法如下:
```java
public static int countChar(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
```
这个方法接收一个字符串 `str` 和一个字符 `c`,并且使用一个循环遍历字符串中的每个字符,如果遍历到的字符和 `c` 相等,就将计数器 `count` 加一。最后返回计数器的值即可。
使用示例:
```java
String str = "hello world";
char c = 'l';
int count = countChar(str, c);
System.out.println(c + " occurs " + count + " times in " + str);
// 输出:l occurs 3 times in hello world
```
java定义一个方法,接收一个字符串和一个字符,统计该字符在字符串中出现的次数。
可以定义一个如下的方法:
```java
public static int countChar(String str, char ch) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
return count;
}
```
其中,`str` 表示要统计的字符串,`ch` 表示要统计的字符。方法内部使用了一个循环遍历字符串中的每个字符,如果遇到了要统计的字符,则计数器 `count` 加 1。最后返回计数器的值即可。
例如,如果要统计字符串 `"hello world"` 中字符 `'o'` 出现的次数,可以这样调用方法:
```java
int count = countChar("hello world", 'o');
System.out.println(count); // 输出 2
```