JAVA字符串简单运用

题目描述:

本题要求实现一个函数,可统计任一字符串中某个字符出现的次数。例如 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;
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值