0
public class Common {

    public static int getCharNumber(Character c) {
        int a = Character.getNumericValue('a');
        int z = Character.getNumericValue('z');
        
        int val = Character.getNumericValue(c);
        if (a <= val && val <= z) {
            return val - a;
        }
        return -1;
    }
    
    public static int[] buildCharFrequencyTable(String phrase) {
        int[] table = new int[Character.getNumericValue('z') - Character.getNumericValue('a') + 1];
        for (char c : phrase.toCharArray()) {
            int x = getCharNumber(c);
            if (x != -1) {
                table[x]++;
            }
        }
        return table;
    }
}

Above algorithm was used for testing whether a string is a permuation of a palindrome and was authored by CtCI (Cracking the Coding Interview).

My question: Why is the getCharNumber method case-insensitive?

I thought it should to be case-sensitive as it only checks for lowercase characters.

Ivo Mori
  • 2,177
  • 5
  • 24
  • 35
Hank
  • 1
  • 2
  • Welcome to Stack Overflow. Please take the [tour](https://stackoverflow.com/tour), read about [what's on-topic](https://stackoverflow.com/help/on-topic), and read [How to Ask a Good Question](https://stackoverflow.com/help/how-to-ask). In particular, I suggest before asking _Why is X_ type of questions [be to sure to have (re)searched](https://meta.stackoverflow.com/q/261592/5698098) for the answer youself (and also include that fact in your question description). Also take care to include the relevant tags; in particular the tag for your programming language `java`. – Ivo Mori Jul 13 '20 at 02:28
  • _As a hint_ check the API documentation for the used classes and methods; i.e. [Character](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Character.html), in particular [getNumericValue(char)](https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue(char)). – Ivo Mori Jul 13 '20 at 02:41

1 Answers1

0

Why is the getCharNumber case-insensitive?

The getCharNumber method uses Java's Character#getNumericValue(char) method for which its JavaDoc states in particular:

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

Meaning that for example for character A and a this API method returns the same value, i.e. 10, and thus there's no case-sensitivity.


For reference, see also

Ivo Mori
  • 2,177
  • 5
  • 24
  • 35
  • So, basically, the "numeric value" is the value the character would represent when used in a base-16, base-32 or base-whatever number representation? Interesting. I'd have expected it to return the ASCII value. –  Jul 13 '20 at 06:57