问题描述
int[] buildCharFreqTable(string phrase){
int[] tab = new int[Character.getNumericValue('z') - Character.getNumericValue('a') + 1];
for (char c : phrase.toCharArray()) {
int x = getCharNumber(c);
if ( x != -1){
tab[x]++;
}
}
return tab;
}
此功能可计算每个字符在一个短语中出现的次数.但我不明白这行
This is a function that counts how many times each characters appear in a phrase. But I don't understand the line
int[] tab = new int[Character.getNumericValue('z') - Character.getNumericValue('a') + 1];
这行代码是做什么的,为什么我们必须使用
What does this line do and why do we have to use
Character.getNumericValue('z') - Character.getNumericValue('a') + 1
预先感谢
推荐答案
此行试图创建一个数组,该数组的每个字符'a'到'z'都有索引.Java与Java用于其他字符的unicode不同,Java实际上使用相同的数字对英语字母的所有变体进行编码."A"和"a"都对应于10,"B"和"b"都对应于11,依此类推.这意味着要不区分大小写地计算英文字母中的每个字符,我们可以创建一个每个字符有一个索引的数组,并增加与我们看到的每个字符相对应的索引值.线
This line is trying to create an array which has an index for each character 'a' to 'z'. Java, unlike unicode which java uses for other characters, actually encodes all variants of English letters using the same numbers. 'A' and 'a' both correspond to 10, 'B' and 'b' both correspond to 11 and so on. This means that to count each character in the English alphabet independent of case, we can create an array with one index per character and increment the value of the index corresponding to each character we see. The line
int[] tab = new int[Character.getNumericValue('z') - Character.getNumericValue('a') + 1];
创建一个新数组,其大小为 z的值-'a'的值+ 1
.在Java中,英文字符按字母顺序给出,因此'a'为10,'z'为35.这使得数组 35-10 + 1
的大小或26(即英文字母中的字母.这比创建简单的大小为26的数组更适合创建该数组.如果要在一行中计算字符"0"到"9"而不是"a"和"z",该怎么办?您可以简单地将"a"和"z"更改为"0"和"9",或将它们作为变量传递.
Creates a new array of size Value of 'z' - Value of 'a' + 1
. In java, English characters are given alphabetically sequential numeric values, so 'a' is 10 and 'z' is 35. This makes the size of our array 35-10+1
or 26, the number of letters in the English alphabet. This is just a more adaptable way to creating that array than simply creating an array of size 26. What if you wanted to count the characters '0' through '9' in a line, instead of 'a' and 'z'? You could simply change the 'a' and 'z' to '0' and '9', or pass them as variables.
这篇关于char频率表中的Character.getNumericvalue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!