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

时间:2018-10-07 00:43:03

标签: java arrays char

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

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 个答案:

答案 0 :(得分:2)

char是无符号的16位数字类型,在用作数组索引时将扩展为int

charSet[c]隐式为charSet[(int) c]

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

答案 1 :(得分:0)

带有我的注释的代码。

    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
    }