如何在考虑标点符号的同时在文件中查找字符串
How to find strings in a file while taking into account the punctuations?
我正在尝试计算某个单词在文本文件中出现的次数。这是我的代码:
int main()
{
ifstream file("Montreal.txt");
string str;
int number = 0;
while (file >> str){
if (str == "Toronto"){
number++;
}
}
cout << number << endl;
return 0;
}
问题是:
当我要找的单词(在本例中为"Toronto")末尾有一个标点符号,如"Toronto."或"Toronto"时,它不会考虑它。我该如何考虑这些情况?
谢谢
使用 std::string::find()
:
if (str.find("Toronto") != std::string::npos)
{
// ...
}
试试这样的事情
#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;
}
}
相关文章:
- 在C++中查找文件
- 在UNIX系统中使用DIR查找文件的字节大小
- 使用gcc从静态链接的文件中查找可选符号
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文件中查找字节序列
- FFMpeg库:如何在音频文件中精确查找
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- g++ -I 和 -L 命令来查找不起作用的 .hpp 文件
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 从文件中查找单词并替换到其他文件中
- 如何从文本文件中查找最常见的字母和出现次数?
- 在代码块中查找输出文件
- 在终端中运行可执行文件与在Mac查找器中打开
- 在链接可执行文件之前查找静态库未解析的依赖项
- 在 elf 文件中查找全局变量的位置
- 在目录中查找所有.cpp.h文件(include,src等)的传统方法
- 查找第一个文件/查找下一个文件不返回文件夹中的所有文件
- C++/哪个文件查找顺序更快
- 在内存中创建gzip文件查找CPP示例
- 使用c++和文件查找曲线下的面积