半泽直树 复仇篇夭折:关于C语言的问题。

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/10 08:44:29
怎么用c语言,编写一段程序实现:
从一段英文文章中统计出所有出现的单词数量,并按字母顺序显示出来。
有没有那位大虾给写点代码?
小弟是个菜鸟刚接触程序,向参考一下。

我觉得应该这样:扫描文章,构造单词表(单词表有单词和单词出现次数组成);
扫描文章时,读到空格,将前面的单词记下,同时查找单词表,如果此时单词表中已经有了这个单词,将该单词的出现次数加一,如果单词表中没有此单词,向单词表中加入这个单词,.
按字母顺序打印出单词表
我用C++写的,给你一个参考,你的文本文件要与这个程序放在一块,然后在命令行下输入完整的文件名,如:Word.txt
#include <iostream.h>
#include <stdio.h>
#include <string>
#include <map>
using namespace std;

void ReadFromFile()
{
/* this function aimed to read words
from a given file
*/
char sFileName[100];
string sWord;
char ch;
map<string,int> mWordMap;
cout<<"please Enter file name:"<<endl;
bool bContact = false;
/*please make sure that the file is the
same directory with the exe program
*/
cin>>sFileName;
FILE *p = fopen(sFileName,"r");
if(p == NULL)
{
cout<<"cannot open the file "<<sFileName<<endl;
return;
}
while(!feof(p))//not the end of the file
//do the following
{
ch = fgetc(p);

if((ch>='a'&&ch<='z')||
(ch>='A'&&ch<='Z'))
{
sWord += ch;
}
else if(ch == '-')
//contact signal
{
bContact = true;
continue;
}
else
{
if(bContact)
{
bContact = false;
continue;
}
mWordMap[sWord]++;
sWord = "";
}

}
int iTotal = 0;// the totle number of the words in the file
typedef map<string,int>::const_iterator CI;
for(CI pm = mWordMap.begin();pm!=mWordMap.end();++pm)
{
iTotal += pm->second;
cout<<(pm->first).data()<<" appear : "<<pm->second<<" times "<<endl;
}
cout<<"there are "<<iTotal<<" words in this file ."<<endl;

}

void main()
{
ReadFromFile();
}

C++中的map有这个功能,就是我上面说的如果有这个单词,就加一,没有则创建,输出是按照先大写后小写的顺序,大小写相同的情况下从a -- z的顺序输出.

本程序有两个算法,一个是计算单词的个数,即是求空格的个数加一,第二个算法是比较各个字母的大小,按顺序输出。程序不是很难。。

郁闷,这个问题不是有人解过了吗?参考书上多得是呀。