【Java】遍历字符串和统计字符个数

一、引入

在之前我们遍历过数组,所谓遍历就是将数组中每一个元素都给获取出来。

现在遍历字符串也是一样的,就是我们需要将字符串里的每一个字符都给拿出来。


二、涉及到的方法

  • public char charAt(int index) :根据索引返回对应的字符

字符串也是有索引的,例如"钢门123吹小雪" 为例,对应的索引分别为 0 1 2 3 4 5 6 7,可以发现,这个跟我们之前数组索引的规则一模一样!

  • public int length():返回此字符串的长度

区分 —— 数组的长度:数组名.length,数组的长度是一个属性,所以我们在调用的时候 length 后面是不加小括号的。而字符串的长度是一个方法,方法在调用的时候 length 是需要加小括号的。

代码示例

package com.itheima.stringdemo;
import java.util.Scanner;

public class StringDemo5 {
    public static void main(String[] args) {
        //1.键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        String str = sc.next();
        //2.进行遍历
        for (int i = 0; i < str.length(); i++) {
            //i 依次表示字符串的每一个索引
            char c = str.charAt(i);
            System.out.println(c);
        }
    }
}

三、练习:统计字符串个数

需求:键盘录入一个字符串,统计该字符串中大写字母字符,小写字母字符,数字字符出现的次数(不考虑其他字符)

package com.itheima.stringdemo;

import java.util.Scanner;

public class StringDemo6 {
    public static void main(String[] args) {
        //1.键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        String str = sc.next();
        //2.统计--- 计数器思想
        //定义三个计数器
        int bigCount = 0;
        int smallCount = 0;
        int numberCount = 0;
        // 如果还需要统计其他字符,只需要再加一个 otherCount 即可
        for (int i = 0; i < str.length(); i++) {
            //i 依次表示字符串中的每一个索引
            char c = str.charAt(i);
            if(c >= 'a' && c <= 'z'){
                //char类型的变量在参与计算的时候自动类型提升为int,在提升的时候就会自动查询ascii码表,变成对应的数字,然后再去进行比较
                smallCount++;
            }else if(c >= 'A' && c <= 'Z'){
                bigCount++;
            // 注:如果写成 "c >= 0 && c <= 9" 就会出问题,因为在ASCII码表中,字符 '0' 所对应的数字其实是 48 ,字符 '9' 所对应的数字其实是57。
            }else if(c >= '0' && c <= '9'){
                numberCount++;
            }
        }

        //3.输出打印
        System.out.println("小写字母有:" + smallCount + "个");
        System.out.println("大写字母有:" + bigCount + "个");
        System.out.println("数字字母有:" + numberCount + "个");
    }
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值