蓝桥杯 统计单词数

蓝桥杯 统计单词数

题目

统计输入英文文章段落中不同单词(单词有大小写之分,但统计时忽略大小写)各自出现的次数。输入段落中所含单词的总数不超过100,最长单词的长度不超过20个字母。

输入格式

一个包含若干句子的段落,每个句子由若干英文单词组成。除空格,逗号和句号外,这些输入的句子中不含其他非字母字符,并且,逗号和句号紧跟在它前面的英文单词后面,中间没有空格。段落最后一个字符是回车符,表示输入结束。

输出格式

若段落中共有M个不同的英文单词,则按照其在段落中出现的先后顺序输出M行,各行的格式为:单词中所有字母均用大写形式输出(最长的单词顶格输出,它前面没有多余的空格;其余单词与其右对齐)+冒号+N个*号+该单词在段落中的出现次数N。

输入样例

1
This is a test. This test is easy. This is a test. This test is easy.

输出样例

1
2
3
4
5
THIS:****4
IS:****4
A:**2
TEST:****4
EASY:**2

思路

c++的string居然没有split(),需要自己实现!strcpy(),strtok()
c++还有一堆小众函数特别好用。
transform()toupper()

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//TOJ1399
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
vector<string> split(const string& str, const string& delim) {
vector<string> res;
if ("" == str) return res;
char * strs = new char[str.length() + 1];
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while (p) {
string s = p;
res.push_back(s);
p = strtok(NULL, d);
}
return res;
}
char op(char c)
{
return toupper(c);
}
int include(vector<string>& v, string& s)
{
if (v.size() == 0)
return -1;
else {
for (unsigned i = 0; i < v.size(); ++i)
{
if (v[i] == s)
{
return i;
}
}
}
return -1;
}

int main(int argc, char const *argv[])
{
vector<string> v;
string in;
getline(cin, in);
transform(in.begin(), in.end(), in.begin(), op);
v = split(in, " ,.");
//统计
vector<string> vs;
vector<int> ints;
for (unsigned i = 0; i < v.size(); i++)
{
int a = include(vs, v[i]);
if (a == -1)
{
vs.push_back(v[i]);
ints.push_back(1);
}
else {
ints[a]++;
}
}
//查找最长单词
unsigned longword = 0;
for (unsigned a = 0; a < vs.size(); a++)
longword = (vs[a].size() > longword) ? vs[a].size() : longword;

for (unsigned i = 0; i < vs.size(); ++i)
{
for (unsigned j = 0; j < longword - vs[i].size(); j++)
cout << " ";
cout << vs[i] << ":";
for (int j = 0; j < ints[i]; j++)
cout << '*';
cout << ints[i] << "\n";
}
return 0;
}
文章作者: Shengyaqingfeng
文章链接: https://creazyboyone.github.io/toj1399/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Shengyaqingfeng's Blog