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

我不太确定为什么这段涉及字符数组的代码有意义?


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 进行比较?


慕容708150
浏览 181回答 2
2回答

三国纷争

Achar是无符号的 16 位数字类型,int当用作数组索引时将被扩展为。charSet[c] 是隐含的 charSet[(int) c]请注意,如果字符串中包含非 ASCII 字符,代码将失败,因为只有ASCII字符在 Unicode 代码点范围 0-127 中。任何其他 Unicode 字符都会导致ArrayIndexOutOfBoundsException.

慕容3067478

带有我的评论的代码。    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    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java