Java 隐式转换 char 到 int?
Java Implicit conversion char to int?
有人给我一道面试题,输出出现频率最高的一个字符。
给定这个字符串 "aaxxaabbaa"。字符'a'出现频率最高。
下面的代码是我在网上搜索到的。注意:我用 2 个循环实现它,效率低下(不同主题)
public static char findMostUsedChar(String str){
char maxchar = ' ';
int maxcnt = 0;
// if you are confident that your input will be only ascii, then this array can be size 128.
// Create a character counter
**int[] charcnt = new int[Character.MAX_VALUE + 1];**
for(int i = 0; i < str.length()-1; i++){
char **ch** = str.charAt(i);
// increment this character's cnt and compare it to our max.
if (**charcnt[ch]**++ >= maxcnt) {
maxcnt = charcnt[ch];
maxchar = ch;
}
}
return maxchar;
}
他们声明了一个 int 数组,在特定索引处找到字符(即 'a'),然后将其用作索引。
在 eclipse 中的调试器上跟踪代码后,我仍然不明白如何使用字符来表示 int 索引而不显式强制转换或使用 charVal.getNumericValue()?甚至大部分S.O。 char 到 int 主题显式转换。
提前致谢。
Array access expressions 进行隐式一元数字提升,这会将表达式扩展为 int
.
The index expression undergoes unary numeric promotion (§5.6.1).
char
数据类型通过其 Unicode 值扩展为 int
,例如'A'
-> 65
.
有人给我一道面试题,输出出现频率最高的一个字符。
给定这个字符串 "aaxxaabbaa"。字符'a'出现频率最高。
下面的代码是我在网上搜索到的。注意:我用 2 个循环实现它,效率低下(不同主题)
public static char findMostUsedChar(String str){
char maxchar = ' ';
int maxcnt = 0;
// if you are confident that your input will be only ascii, then this array can be size 128.
// Create a character counter
**int[] charcnt = new int[Character.MAX_VALUE + 1];**
for(int i = 0; i < str.length()-1; i++){
char **ch** = str.charAt(i);
// increment this character's cnt and compare it to our max.
if (**charcnt[ch]**++ >= maxcnt) {
maxcnt = charcnt[ch];
maxchar = ch;
}
}
return maxchar;
}
他们声明了一个 int 数组,在特定索引处找到字符(即 'a'),然后将其用作索引。 在 eclipse 中的调试器上跟踪代码后,我仍然不明白如何使用字符来表示 int 索引而不显式强制转换或使用 charVal.getNumericValue()?甚至大部分S.O。 char 到 int 主题显式转换。
提前致谢。
Array access expressions 进行隐式一元数字提升,这会将表达式扩展为 int
.
The index expression undergoes unary numeric promotion (§5.6.1).
char
数据类型通过其 Unicode 值扩展为 int
,例如'A'
-> 65
.