Character.getNumericvalue in char Frequency table

妖精的绣舞 提交于 2021-01-27 16:56:29

问题


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

Thanks in advance


回答1:


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];

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.



来源:https://stackoverflow.com/questions/44711311/character-getnumericvalue-in-char-frequency-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!