我正在尝试计算某个单词出现在文本文件中的次数。这是我的代码:
int main()
{
ifstream file("Montreal.txt");
string str;
int number = 0;
while (file >> str){
if (str == "Toronto"){
number++;
}
}
cout << number << endl;
return 0;
}
问题是:
当我正在寻找的单词(在这种情况下,'多伦多')最后有一个标点符号,如“多伦多”。或“多伦多”,它不考虑它。如何将这些案例考虑在内?
由于
答案 0 :(得分:2)
使用std::string::find()
:
if (str.find("Toronto") != std::string::npos)
{
// ...
}
答案 1 :(得分:0)
尝试这样的事情
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
#include <sys/stat.h>
const size_t nErrSize = std::numeric_limits<size_t>::max();
int CountWord(const std::string &sBuff, const std::string sWord)
{
size_t nNext = 0;
int nCount = 0;
int nLength = sWord.length();
while (sBuff.npos != (nNext = sBuff.find(sWord, nNext)))
{
++nCount;
nNext += nLength;
}
return nCount;
}
#if defined(WIN32)
#undef stat
#define stat _stat
#endif
size_t GetFileSize(const std::string &sFile)
{
struct stat st = { 0 };
if (0 > ::stat(sFile.c_str(), &st))
return nErrSize;
else
return st.st_size;
}
bool Load(const std::string &sFile, std::string &sBuff)
{
size_t nSize = GetFileSize(sFile);
if (nSize == nErrSize)
return false;
std::ifstream ifs(sFile, std::ifstream::binary);
if (!ifs)
return false;
std::vector<char> vBuff(nSize);
ifs.read(vBuff.data(), nSize);
if (ifs.gcount() != nSize)
return false;
sBuff.assign(vBuff.cbegin(), vBuff.cend());
return true;
}
int main()
{
const std::string sFile("Montreal.txt");
const std::string sSearch("Toronto");
std::string sBuff;
if (Load(sFile, sBuff))
{
std::cout << sSearch
<< " occurred "
<< CountWord(sBuff, sSearch)
<< " times in file "
<< sFile
<< "."
<< std::endl;
return 0;
}
else
{
std::cerr << "Error" << std::endl;
return 1;
}
}