对一篇文章中所有不同的单词出现的次数进行统计,主要的思想步骤是:
(1)创建一个带有计数的结构
class Words
{
public:
Words(string str)
{
count=1;
word=str;
next=NULL;
}
int count; //出现的次数
string word;
Words *next;
};
(2)方便找同样的单词,每次需要在已有的单词库里搜索比较,可以使用链表的数据结构,每增加一个新单词便在链表尾加一个;相同单词则该单词计数加1。
class WordList
{
public:
void AddWord(string word); //添加单词
bool WordExist(string word); //判断单词是否存在
void WordPrint();
int getLength(){ return length;}//单词链表长度
int getTotal(){ return total;} //输入单词总数
WordList();
~WordList();
private:
Words *first;
Words *last;
int length;
int total;
};
各成员函数实现方式如下
WordList::WordList()
{
first=new Words(" ");
first->next=NULL;
last=first;
length=0;
total=0;
}
WordList::~WordList()
{
Words *p=first;
Words *q;
while(p!=NULL)
{
q=p;
p=p->next;
delete q;
}
}
void WordList::AddWord(string word)
{
if( !WordExist(word) )//单词不存在
{
Words *node=new Words(word); //新建一个参数为word的Words类
last->next=node;
last=node;
last->next=NULL;
length++;
}
}
bool WordList::WordExist(string word)
{
Words *p=first->next;
total++;
while(p!=NULL)
{
if( p->word == word )
{
p->count++;
return true;
}
p=p->next;
}
return false;
}
void WordList::WordPrint()
{
cout<<setw(20)<< setiosflags( ios::left )<<"单词"<<setw(20)<< setiosflags( ios::left )
<<"出现次数"<<setw(20)<<endl;
Words *p=first->next;
for( int i=0; i<length; i++ )
{
string str=p->word;
int max=p->count;
p=p->next;
cout<<setw(20)<< setiosflags( ios::left )<<str<<setw(20)<< setiosflags( ios::left ) <<max<<endl;
}
}
(3)读取文本,挑取单词放入string中,并统计处理
class Text
{
string txt;
WordList mywords;
public:
void PutIn();
void PutOut();
void Run();
};
void Text::PutIn()
{
ifstream file("in.txt");
if(!file)
{
cout<<"cannot open!"<<endl;
}
getline(file,txt);
}
void Text::Run()
{
int i=0;
while( i<txt.length())
{
string temp;
while( !isalpha(txt[i])&&txt[i]!='+' && i<txt.length())
{
i++;
}
while( isalpha(txt[i]) || txt[i]=='+' && i<txt.length())//如果参数是字母字符
{
temp=temp+txt[i]; //string的用法注意
i++;
}
if(i<txt.length())
{
mywords.AddWord(temp);
}
}
}
void Text::PutOut()
{
mywords.WordPrint();
}
主函数为
void main()
{
Text mytest;
mytest.PutIn();
mytest.Run();
mytest.PutOut();
}
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <string>
using namespace std;
int main (){
map<string, int> mp;
map<string, int> :: iterator it;
printf("input text(line with only # for end):\n");
string s;
while(cin >> s && s!="#"){
mp[ s ] ++;
}
cout << "word\ttime" << endl;
for(it=mp.begin(); it!=mp.end(); ++it){
cout << it->first << "\t" << it->second << endl;
}
system("pause");
return 0;
}
简单了很多很多!