Java函数编写:计算字符串中某个字符出现的次数
发布时间:2023-07-04 18:04:42
要计算字符串中某个字符出现的次数,可以使用以下 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 是要计算次数的字符。
函数首先创建一个变量 count 来存储字符出现的次数,并初始化为 0。然后使用 for 循环遍历字符串的每个字符。
在循环中,使用 str.charAt(i) 获取字符串中的第 i 个字符。如果该字符与目标字符 c 相等,就将 count 增加 1。
最后,函数返回 count,即字符 c 在字符串 str 中出现的次数。
以下是一个示例演示如何使用该函数:
public class Main {
public static void main(String[] args) {
String str = "Hello World!";
char c = 'o';
int count = countChar(str, c);
System.out.println("Character '" + c + "' appears " + count + " times in the string.");
}
}
输出结果为:
Character 'o' appears 2 times in the string.
这个例子中,我们统计了字符 'o' 在字符串 "Hello World!" 中出现的次数,结果为 2。
