以字母d或e结尾的单词的个数
题目描述:
给定一文件,各字符串间以逗号隔开,计算以字母d或e结尾的单词的个数
输入示例:
abc,abd,ade,ade,ase,ade,abd,aft,agy,ax,ase,aac,aad
输出示例:
{abd=2,ade=3,ase=2}
解题思路:
通过int pos=s.find()找到’,’,再使用s[pos-1]判断当前字符串的最后一个字母是否‘d’ 或 ‘e’,若是则用s.substr()截取字符串并插入map中,若不是则继续寻找下一个字符串。直至遍历结束,将map中数据按要求输出。
完整代码:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
map<string, int> m;
int p = 0;
int pos = s.find(',');
while (p<s.size() && (pos - 1)<s.size())
{
if (s[pos - 1] == 'd' || s[pos - 1] == 'e') //字符串最后一个字符是d或e
{
string ret = s.substr(p, pos - p); //)截取字符串
m[ret]++; //插入map中
}
p = pos + 1;
pos = s.find(',', p);
}
cout << "{";
auto it = m.begin();
for (int i = 0; i < m.size() - 1; i++) //按要求格式输出
{
cout << it->first << "=" << it->second << ",";
it++;
}
cout << it->first <<"="<< it->second << "}" << endl;
system("pause");
return 0;
}
58同城另一编程题:求字符串中字母重叠的次数
哇哦,实在太菜了,导致做题时间总是不够,难过ing…