我不太確定為什么這段涉及字符數組的代碼有意義?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 回答

慕容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
}
添加回答
舉報
0/150
提交
取消