统计单词数

code

#include<cstring>
#include<iostream>
#include<vector>
#include<sstream>
#include<algorithm>
#include<iomanip>
using namespace std;
struct Node{
	string str;
	int time=1;
	Node(string s){//initial function 
		str=s;
	};
};
int main()
{
	ios::sync_with_stdio(false);
	vector<Node> vec;
	string str;
	getline(cin,str);
	istringstream is(str);//cut sentences by spaces
	string s;
	int flag=0;
	int i=0;
	int max_len=0;
	while(is>>s){
		//remove '.,' and to upper
		if(s.find('.')!=-1){
			s.erase(s.find('.'),1);
		}else if(s.find(',')!=-1){
			s.erase(s.find(','),1);
		}
		transform(s.begin(),s.end(),s.begin(),::toupper);//source begun and end,target place,funtion point
		
		if(s.length()>max_len){
			max_len=s.length();
			
		}
		Node  *n=new Node(s);
		for(i=0;i<vec.size();++i){
			if(n->str==vec[i].str){
			flag=1;
			break;
			}
		}
		if(flag==0){
			vec.push_back(*n);
		}else {
			vec[i].time++;
			flag=0;
		}
	}
	for(i=0;i<vec.size();++i){
		cout<<setw(max_len)<<vec[i].str<<':';
		for(int j=0;j<vec[i].time;++j){
			cout<<'*';
		}
		cout<<vec[i].time<<'\n';
	}
	return 0;
}

des

资源限制
时间限制:1.0s   内存限制:512.0MB
问题描述
  统计输入英文文章段落中不同单词(单词有大小写之分,  但统计时忽略大小写)各自出现的次数。 输入段落中所含单词的总数不超过100,最长单词的长度不超过20个字母.
输入格式
  一个包含若干句子的段落, 每个句子由若干英文单词组成. 除空格,  逗号和句号外, 这些输入的句子中不含其他非字母字符, 并且, 逗号和句号紧跟在它前面的英文单词后面, 中间没有空格. 段落最后一个字符是回车符,  表示输入结束.
输出格式
  若段落中共有M个不同的英文单词,则按照其在段落中出现的先后顺序输出M行,各行的格式为:  单词中所有字母均用大写形式输出(最长的单词顶格输出,它前面没有多余的空格;  其余单词与其右对齐)+冒号+N个*号+该单词在段落中的出现次数N
样例输入
This is a test. This test is easy. This is a test. This test is easy.

样例输出


THIS:****4
  IS:****4
   A:**2
TEST:****4
EASY:**2
posted @ 2022-02-13 16:15  ethon-wang  阅读(54)  评论(0编辑  收藏  举报