用char减去char是什么意思

用char减去char是什么意思

本文介绍了Java:用char减去char是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近在执行程序时,我遇到了一个问题.下面是程序的一部分

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

我猜想它正在递增lettercounts数组中特定字符的值(最初为0);我猜'a'的索引为0,'z'的索引为25.但是我想了解那小段代码是如何工作的.

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'

是一种获取字符在字母表中位置的巧妙方法. 'a' - 'a'会给您0.'b' - 'a'会给您1.'c' - 'a'会给您2,依此类推.

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.

值得注意的是,如果字符串中包含除a-z以外的任何其他字符(包括大写字符),则此操作将中断,并且您会看到 IndexOutOfBoundsException

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

这篇关于Java:用char减去char是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 00:39