首页 > 解决方案 > ++letter[c - 'A']; 是什么意思?在这个C程序中是什么意思?

问题描述

我有以下程序,它计算文本文件中每个大写字母的出现次数。我正在评论每一行以了解程序在执行时发生了什么,但是我在下面的行中迷路了++letter[c - 'A'];。我无法得到它,我认为它是假设收集这封信并存储这封信出现的暨。但是符号 c - 'A',对我来说有点陌生。

void main(argc,argv)
   int argc;
   char *argv[];
   {
   int c, i, letter[26];
   FILE    *ifp, *ofp, *fopen(); // pointers to in file and output file pointer

  if (argc != 3) /* if the number of arguments is not equal to 3 */
      printf("\nusage: %s infile outfile\n\n", argv[0]); // prints the following
      // message "usage letter infile outfile */
  else { // if the number of arguments is three 
      ifp = fopen(argv[1], "r"); // opens the first file (pointer to file 
      // in reading mode //
      ofp = fopen(argv[2], "w"); // then opens the the second argument "second
      // file in writting mode. // 
      for (i = 0; i < 26; ++i) /* initialize array to zero */
          letter[i] = 0; // makes every element in the array of 26 to 0, in other
          // words the counter for every letter to 0
      while (( c=getc(ifp)) != EOF) // gets the characters (next of a file)
          if ('A' <= c && c <= 'Z') // if the character found is an uppercase 
          // character between A and Z
              ++letter[c - 'A']; // 
      for (i = 0; i < 26; ++i) {
          if (i % 6 == 0)
              fprintf(ofp, "\n");
          fprintf(ofp, "%5c: %5d", 'A' + i, letter[i]);
          }
          fprintf(ofp, "\n\n");
      }
  }

标签: cchar

解决方案


它计算每个字母出现的次数。


'A'只是一个数字。在基于 ASCII 的机器上,'A'只是另一种写法65

ASCII中,26 个拉丁大写字母是连续找到的,所以,

  • 'A'-'A'=0
  • 'B'-'A'=1
  • 'C'-'A'=2
  • ...
  • 'Z'-'A'=25

(请注意,此代码在EBCDIC机器上不起作用,因为字母在该编码中不连续。)

因此为每个字母letter[c - 'A']产生一个独特的元素。letter

最后,++x增加 的值x,因此增加与 中的字母相对应++letter[c - 'A']的元素。letterc

例如,如果我们读入ABRACADABRA,我们最终会得到

int letter[26] = {
    /* A  B  C  D  E  F  G  H  I  J  K  L  M */
       5, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    /* N  O  P  Q  R  S  T  U  V  W  X  Y  Z */
       0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0
};

推荐阅读