题目描述:
本题要求实现一个函数,可统计任一字符串中某个字符出现的次数。例如 abcda 中,a 出现了 2 次,b 出现了 1 次.
函数接口定义:
函数的原型如下:
public static int countChar(String string, char c);
其中 string
和 c
都是用户传入的参数。
string
的长度在区间 [1,1000][1,1000] 以内; c
是一个可能出现在字符串中的字符。函数须返回 string
中 c
出现的次数。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.*;
public class Main {
/* 此区间是要编写的函数 */
public static int countChar(String string, char c) {
//请补充完整
}
/* 此区间是要编写的函数 */
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String s1 = key.nextLine();
String s2 = key.nextLine();
System.out.println(countChar(s1, s2.charAt(0)));
}
}
输入样例:
在这里给出一组输入。例如:
abca
a
输出样例:
在这里给出相应的输出。例如:
2
代码实现:
public static int countChar(String string, char c) {
int count=0;
for (int i = 0; i < string.length(); i++) {
if(string.charAt(i)==c){
count++;
}
}
return count;
}