c - ++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");
}
}
解决方案
它计算每个字母出现的次数。
'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']
的元素。letter
c
例如,如果我们读入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
};
推荐阅读
- ruby - Watir运行错误
- python - Why use class method over a regular function in python
- python - 如何使用 Python 连接 SQLite DB 中的两个表?
- c++ - 将 CURL 作为静态库添加到 C++ CMake 项目
- android - 使用 minifyEnabled true 后的 android studio 错误
- android - Navigation Drawer 项目应该是静态的还是动态的?
- ubuntu - 无法在 ubuntu 16.04 上启动 meld,因为错误 import meld.conf
- listview - 无法将水平可滚动的 ListView 包装在 Column 中
- javascript - 浏览器中的 Wacom 取消移动
- python - 如何在python中提取部分字符串(字符串长度可能会有所不同)