代码实践
#include <iostream>
using namespace std;
#include <string>
#include <map>
#include <fstream>
int Number_of_words(ifstream& ifs)
{
if (!ifs)
{
cerr << "file open" << endl;
return 0;
}
string words;
map<string, int> twords;
twords["Python/python"] = 0;
while (ifs >> words)
{
//统计 Python 单词
string sub1 = "Python";
int index1 = 0;
while ((index1 = words.find(sub1, index1)) < words.length())
{
index1++;
twords["Python/python"]++;
}
//统计 python 单词
string sub2 = "python";
int index2 = 0;
while ((index2 = words.find(sub2, index2)) < words.length())
{
index2++;
twords["Python/python"]++;
}
}
return twords["Python/python"];
}
int main()
{
//map<string, int> words;
words["hehe"] = 1;
字数统计
//string tword;
//while (cin >> tword)
//{
// words[tword]++;
// if (cin.get() == '\n')
// {
// break;
// }
//}
打印单字及其出现的次数
//map<string, int>::iterator iter = words.begin();
//for (; iter != words.end(); iter++) //注意这里是end(),不是begin(),不要写错了
//{
// cout << iter->first << ' ' << iter->second << endl;
//}
//检查是否key存在的三种方法
#if 0
cout << "方法1" << endl;
cout << words["hmj"] << endl;
#endif
#if 0
cout << "方法2" << endl;
//words["hmj"] = 1;
map<string, int>::iterator it = words.find("hmj");
if (it != words.end())
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
#endif
#if 0
cout << "方法3" << endl;
words["hmj"] = 10;
words["hmj"] = 100;
cout << words.count("hmj") << endl; //count在map中值为1或者0(感觉可以理解成bool类型)
#endif
//统计ptyhon.txt中"python"与"Python"一共出现的次数
ifstream ifs("python.txt");
cout << "一共出现了:" << Number_of_words(ifs) << "次!" <<endl;
system("pause");
return 0;
}
今天还是20200311 STL太强了