C语言问题,一篇文章列出字母等等

来源:百度知道 编辑:UC知道 时间:2024/06/04 13:47:47
导入一篇文章之后,如何列出字母以及出现的字数,不要求按字母顺序。

还有就是我排列之后会出现各种标点,符号,不知道会不会影响后面的程序。

最好能写出一个大概程序,尽量用简单的语言,因为现在语法刚开始学,但是基本的function以及array 或者各种loop以及porinter是需要用的。

谢谢
不好意思,前面打错了,是出现字母的次数,不是字数

/*
算法:
把文件一个字符一个字符读入,用一个大小为256的int型数组,每读一个字符,就把它对应的数组元素值加1。最后输出字母的部分。也可以只统计字母部分。
说明:
这里没有涉及文件,用的是标准输入输出,用文件的话把getchar()换成fgetc()就可以了
*/

#include <stdio.h>

int main()
{
int c;
int chnum[256] = {0}; /* 初始化全为0 */
while ( (c = getchar()) != EOF )
chnum[(unsigned char)c]++;
for (c = 'a'; c <= 'z'; ++c)
printf("%c: %d times.\n", c, chnum[c]);
for (c = 'A'; c <= 'Z'; ++c)
printf("%c: %d times.\n", c, chnum[c]);
return 0;
}

最简单的就是用映射表map:

// test.cpp
#include <iostream> // for I/O
#include <cassert> // for std::assert()
#include <map> // for std::map
#include <utility> // for std::make_pair
#include <cstddef> // for std::size_t
#include <fstream> // for file I/O
#include <sstream&