“ch - 'a'”是什么意思?

abh*_*dey 0 java arrays

我正在浏览一段我无法理解的代码。考虑与我们的社区核实这一点。

在下面的代码中,我无法理解 line count[ch-'a']++ 的作用。或者我们如何在 java 7 中编写相同的内容。解释说我们有一个 String s 和一个 int 数组计数。我们遍历字符串 s 并计算 s 中字符出现的次数,并将 count 的频率放入数组中。请帮忙!!

String s = "test";
   int[] count = new int[26];        
   for (int i = 0; i < s.length(); i++) {
       char ch = s.charAt(i);
       count[ch-'a']++;                     
   }
Run Code Online (Sandbox Code Playgroud)

Ang*_*Koh 5

代码试图计算每个字符出现的次数。

它分配它使得

a occupies position 0
b occupies position 1
etc etc
Run Code Online (Sandbox Code Playgroud)

要获得位置 0,您需要调用 'a' - 'a'
以获得位置 1,您需要调用 'b' - 'a'

那么“count[ch-'a']++;”中发生了什么 相当于

int position = ch -'a'; // get position
count[position] = count [position] + 1; // increment the count in that particular position
Run Code Online (Sandbox Code Playgroud)