效果:
代码:
#include <iostream>
#include <map>
#include <string>
int main()
{
std::string s;
//std::cin >> s;
s = " aaa aaaaa a aa aaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa Hi I am a person a a a a a I Hi hi I AM FM";
std::cout << s << std::endl;
//创建map容器
std::map<std::string, int>Map;
//分割单词
int i, j;
i = j = 0;
while (s[i] != '\0')
{
while (s[i] == ' ')
{
i++;
}
j = i;
while (s[j] != '\0' && s[j] != ' ')
{
j++;
}
//截取字符串
std::string tmp = s.substr(i, j - i + 1);
//std::cout << tmp << std::endl;
if (Map.find(tmp) == Map.end())
{
Map.insert(std::pair<std::string,int>(tmp,1));
}
else
{
//auto it = Map.find(tmp);
//it->second++;
Map[tmp]++;
}
i = j;
}
//输出结果
for (auto it = Map.begin(); it != Map.end(); it++)
{
std::cout << it->first << "\t" << it->second << std::endl;
}
return 0;
}