【问题标题】:How to compare array of characters to Boolean如何将字符数组与布尔值进行比较
【发布时间】:2018-10-07 00:43:02
【问题描述】:

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

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

【问题讨论】:

  • 我不明白这个问题。
  • 零是整数,不是布尔值
  • 您希望在什么语句中看到错误以及什么错误?

标签: java arrays char


【解决方案1】:

char 是一个无符号的 16 位数字类型,当用作数组索引时将扩大到 int

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

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

【讨论】:

    【解决方案2】:

    我的 cmets 的代码。

        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
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多