为了账号安全,请及时绑定邮箱和手机立即绑定

如何将字符数组与布尔值进行比较

如何将字符数组与布尔值进行比较

慕容708150 2021-11-03 14:18:10
我不太确定为什么这段涉及字符数组的代码有意义?String str1 = "Hello"int[] charSet = new int[128];char[] chars = str1.toCharArray();    for (char c : chars) { // count number of each char in s.        if (charSet[c] == 0)++charSet[c];    }我的问题是如何将 char 变量作为 charSet 数组的索引并将其与 0 进行比较?
查看完整描述

2 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

Achar是无符号的 16 位数字类型,int当用作数组索引时将被扩展为。

charSet[c] 是隐含的 charSet[(int) c]

请注意,如果字符串中包含非 ASCII 字符,代码将失败,因为只有ASCII字符在 Unicode 代码点范围 0-127 中。任何其他 Unicode 字符都会导致ArrayIndexOutOfBoundsException.


查看完整回答
反对 回复 2021-11-03
?
慕容3067478

TA贡献1773条经验 获得超3个赞

带有我的评论的代码。


    String str1 = "Hello";

    int[] charSet = new int[128];// ascii chars a-z and A-Z go from 65-122 using a 128 array is just being lazy

    char[] chars = str1.toCharArray();

    for (char c : chars) { //loop though each character in the string

        if (charSet[c] == 0)//c is the character converted to int since it's all a-z A-Z it's between 65 and 122                                

            ++charSet[c];//if it the character hasn't been seen before set to 1

    }


查看完整回答
反对 回复 2021-11-03
  • 2 回答
  • 0 关注
  • 176 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信