简体   繁体   English

Java:用char减去char是什么意思?

[英]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; 我猜它是在特定字符的lettercounts数组中递增值(最初为0); I'm guessing index of 'a' is 0 and 'z' is 25. But I want to understand how that little piece of code works. 我猜测'a'的索引是0而'z'是25.但我想了解这段代码是如何工作的。

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. 'a' - 'a'会给你0.'b 'b' - 'a'会给你'c' - 'a'会给你2,依此类推。

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 值得注意的是,如果字符串中包含除az之外的任何字符(包括大写字符),则会中断,并且您会看到IndexOutOfBoundsException

This basically just converts the character ('a' in your example) to the letter number in the alphabet it represents. 这基本上只是将字符(在您的示例中为“a”)转换为它所代表的字母表中的字母数字。 'a' actually has an ASCII(technically utf-16, whose first 255 values are ASCII values) number value (97). 'a'实际上有一个ASCII(技术上是utf-16,其前255个值是ASCII值)数值(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. 因此,如果char为'b',则将访问数组的第二个元素(位置1,98-97 = 1)。 If the char is 'z', then the 26th element of the array will be acessed (at position 25). 如果char是'z',则数组的第26个元素将被访问(在位置25)。 You can easily find an ASCII-value table by typing in "ASCII table" in a search engine. 您可以通过在搜索引擎中键入“ASCII表”轻松找到ASCII值表。

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). 注意:您不能在小写和大写字母之间执行此操作,因为它们具有完全不同的ASCII值('A',例如是65,而'a'是97)。

char variables in Java are numerical values. Java中的char变量是数值。 Therefore, subtracting 'a' from the value of c will give its offset from the beginning of the alphabet. 因此,从c的值中减去'a'将使其偏离字母表的开头。 This allows you to use this value as an array index, as you have correctly guessed. 这允许您将此值用作数组索引,正如您已正确猜到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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