统计字符串中大写字母、小写字母、数字字符的数量

统计字符串中大写字母、小写字母、数字字符的数量

public static void work3(String info){
    //定义三个变量
    int upperNum = 0;//大写
    int lowerNum = 0;//小写
    int digitalNum = 0;//数字

    //Character:包装类
    //Character 类在对象中包装一个基本类型 char 的值
    for (int i = 0;i <info.length();i++){
       char c = info.charAt(i);// charAt(int index):指定索引index处的char值
        if (Character.isDigit(c)){//判断是否为数字
            digitalNum++;
        }else if (Character.isLowerCase(c)){//判断是否为小写
            lowerNum++;
        }else if (Character.isUpperCase(c)){//判断是否为大写
            upperNum++;
        }
    }

//测试类

public class work {
    public static void main(String[] args) {

        work3("appleXIAOmisu7");
       
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用指针法统计字符串大写字母小写字母、空格和数字个数的示例代码: ```c++ #include <iostream> #include <cstring> using namespace std; int main() { char str[100]; int upper = 0, lower = 0, space = 0, digit = 0; cout << "Enter a string: "; cin.getline(str, 100); char *ptr = str; while (*ptr != '\0') { if (*ptr >= 'A' && *ptr <= 'Z') upper++; else if (*ptr >= 'a' && *ptr <= 'z') lower++; else if (*ptr == ' ') space++; else if (*ptr >= '0' && *ptr <= '9') digit++; ptr++; } cout << "Upper case letters: " << upper << endl; cout << "Lower case letters: " << lower << endl; cout << "Spaces: " << space << endl; cout << "Digits: " << digit << endl; return 0; } ``` 首先,我们声明一个字符数组 `str`,用于存储输入的字符串。然后,我们声明四个变量 `upper`、`lower`、`space` 和 `digit`,分别用于存储大写字母小写字母、空格和数字个数。 接下来,我们使用 `cin.getline()` 函数从标准输入读取字符串,并将其存储到 `str` 数组。 然后,我们声明一个字符指针 `ptr`,并将其初始化为 `str`,指向字符串的第一个字符。接着,我们使用 `while` 循环遍历字符串的每个字符,直到遇到字符串的结尾符 `\0`。 在循环,我们使用 `if` 语句判断当前字符是否为大写字母小写字母、空格或数字,并根据判断结果将相应的计数器加一。 最后,我们输出计数器的值,即为统计结果。 注意,在本示例,我们使用了字符的 ASCII 码值来进行判断。大写字母的 ASCII 码值范围为 65~90,小写字母的 ASCII 码值范围为 97~122,空格的 ASCII 码值为 32,数字的 ASCII 码值范围为 48~57。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值