使用 C++,假设我有一个文件,我正在寻找一个关键字,但我不希望它的相邻字符是 a-z
或 0-9
.
假设我想在这样的文件中查找关键字 U
:
U 1.2;
Under 2.3;
abcdUefg;
我希望出现第一行,而不是第二行或第三行。但请注意以下内容也可以。
"(U|B|tau)"
因为这里的 U
是一个单词。
重点是,我要查找的关键字是一个独立的词,而不是该词的一部分。最好的方法是什么?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string line;
vector<string> lines;
ifstream myfile ("FILE");
if (myfile.is_open())
{
while (myfile.good())
{
getline(myfile,line);
lines.push_back(line);
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
for (unsigned i = 0; i < lines.size(); ++i)
{
if (lines[i].find("keyName") != string::npos)
{
printf("Key found!\n");
}
}
myfile.close();
return 0;
}
最佳答案
假设字符串是 ASCII a-z 和 0-9 你可以这样做..
for (unsigned i = 0; i < lines.size(); ++i)
{
size_t pos = lines[i].find("keyName");
size_t len = std::string("keyName").length();
if (pos != string::npos)
{
if(!std::isalnum(lines[i][pos+len+1]))
printf("Key found!\n");
}
}
其中isalnum
如果它是 0-9 或 a-z 并且位于 <cctype>
中,则返回真
关于c++ - 在 C++ String 中寻找一种好方法来查找关键字,而相邻字符不是 a-z,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868173/