用Java中的char索引进行数组访问 [英] Array access with char index in Java

查看:291
本文介绍了用Java中的char索引进行数组访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网上看到有关Java编程练习的解释时,我遇到了以下代码:

While seeing the explanation for a Java programming exercise online, I came upon the following piece of code:

int[] count = new int[128];
int length = 0;
for(char c: s.toCharArray()){
    if(++count[c] == 2){
        length += 2;
        count[c] = 0;
    }
}

我了解代码的功能,但我不知道它如何使用char索引(即,count [c],其中c是char)访问数组元素.我以为索引只能是整数?

I understand what the code does but I don't know how it can access an array element using a char index (i.e.count[c], where c is a char). I thought indexes could only be integers?

推荐答案

char(16位)是int(32位),反之亦然.这是一个隐式转换,特别是char到unsigned int. 在这种情况下,索引可能是代表此字符的ASCII码(对于ASCII字符).

A char (16 bit) is an int (32 bit), not vice versa. This is an implicit casting, char to unsigned int in particular. In this case, the index will probabily be the ASCII code representing this char (for ASCII characters).

这篇关于用Java中的char索引进行数组访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆