Java函数示例:如何统计字符串中指定字符出现的次数
发布时间:2023-06-09 23:28:04
在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;
}
在这里,我们定义了一个名为countChar的函数,它接受两个参数:一个字符串str和一个字符ch。
在函数的主体内部,我们使用一个循环来遍历字符串str中的每一个字符。如果当前字符与指定的字符ch相同,则计数器count加1。
当循环结束后,我们返回计数器count的值,也就是指定字符在字符串中出现的次数。
下面是一个完整的示例程序,它演示了如何使用countChar函数来统计字符串中指定字符的出现次数:
public class Main {
public static void main(String[] args) {
String str = "hello world";
char ch = 'l';
int count = countChar(str, ch);
System.out.println("The character '" + ch + "' appears " +
count + " times in the string \"" + str + "\".");
}
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;
}
}
输出结果如下:
The character 'l' appears 3 times in the string "hello world".
总之,使用Java的String类中的charAt()方法和一个简单的循环可以方便地统计字符串中指定字符的出现次数。
