字符串查找、处理练习 - 统计子串数量、统计字符出现次数

统计子串数量

需求:

1.统计“abc”在字符串“abcdabcfgh”中出现的次数

2.借助于 int indexOf ( String str, int fromIndex )

代码实现:

public class Ex1 {
    public static void main(String[] args) {
        // 定义字符串
        String s = "abcdabcfgh";
        // 定义计数器
        int count = 0;
        // 定义索引值
        int fromIndex = 0;
        // 循环
        while ((fromIndex = s.indexOf("abc", fromIndex)) != -1) {
            // 计数器+1
            count++;
            fromIndex++;
        }

        // 输出结果
        System.out.println("出现的次数"+count);
    }
}

统计字符出现次数

需求:

1.遍历获取字符串中的每一个字符"abc001DEF"

2.统计该字符串中大写字母字符、小写字母字符,数字字符出现的次数(不考虑其他字符)

代码实现:

public class Ex2 {
    public static void main(String[] args) {
        // 定义字符串
        String s = "abc001DEF";
        // 定义计数器
        int countUpper = 0;
        int countLower = 0;
        int countDigital = 0;
        // 遍历字符串
        for (int i = 0; i < s.length(); i++) {
            // 取出来每个字符
            char c = s.charAt(i);
            // 做判断
            if (c >= 'a' && c <= 'z') {
                countLower++;
            } else if (c >= 'A' && c <= 'Z') {
                countUpper++;
            }else{
                countDigital++;
            }
            // 相应计数器+1


        }
        // 循环结束
        // 输出结果
        System.out.println("小写:"+countLower);
        System.out.println("大写:"+countUpper);
        System.out.println("数字:"+countDigital);

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值