简体   繁体   中英

Java: What does subtracting a char by a char mean?

Recently while going through a program I ran into a question. Below is part of the program

public static int numberNeeded(String first, String second) {
        int[] lettercounts = new int[26];
        for(char c : first.toCharArray()){
            lettercounts[c-'a']++;
        }

I don't understand what this line of code does:

lettercounts[c-'a']++;

I guess that it's incrementing the value (which is initially 0) in lettercounts array for the particular character; I'm guessing index of 'a' is 0 and 'z' is 25. But I want to understand how that little piece of code works.

The goal is count the occurrences of each character.

c - 'a'

is a kind of clever way to get the position of the character in the alphabet. 'a' - 'a' would give you 0. 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.

That value is used as an index into the array (which as you correctly stated is initialised with zeros) and the count is incremented.


It's worth noting that this will break if any character other than az is present in the string (including uppercase characters), and you'd see an IndexOutOfBoundsException

This basically just converts the character ('a' in your example) to the letter number in the alphabet it represents. 'a' actually has an ASCII(technically utf-16, whose first 255 values are ASCII values) number value (97). So do all other chars. So, if the char is 'b', then the second element of the array (at position 1, 98 - 97 = 1) will be accessed. If the char is 'z', then the 26th element of the array will be acessed (at position 25). You can easily find an ASCII-value table by typing in "ASCII table" in a search engine.

int a = 'b' - 'a';

Is the same as:

int b = 98 - 97;

NOTE: You can't do this between lowercase and uppercase letters, since they have completely different ASCII values ('A', for example is 65, whereas 'a' is 97).

char variables in Java are numerical values. Therefore, subtracting 'a' from the value of c will give its offset from the beginning of the alphabet. This allows you to use this value as an array index, as you have correctly guessed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM