我有一个文本文件,其中包含以下文本
许可证="123456"
GeneralLicense ="56475655"
我想搜索License以及GeneralLicense.
while (getline(FileStream, CurrentReadLine))
{
if (CurrentReadLine.find("License") != std::string::npos)
{
std::cout << "License Line: " << CurrentReadLine;
}
if (CurrentReadLine.find("GeneralLicense") != std::string::npos)
{
std::cout << "General License Line: " << CurrentReadLine;
}
}
Run Code Online (Sandbox Code Playgroud)
由于单词License也出现在单词中GeneralLicense所以if-statement在行中if (CurrentReadLine.find("License") != std::string::npos)变为真实两次.
如何指定我要搜索确切的子字符串?
更新:我可以按照一些答案提到的顺序撤销或检查是否License在索引零处.但是没有任何ROBOUST(旗帜或其他东西)我们可以精确地寻找完全匹配(像我们在大多数编辑器中那样的东西,例如MS Word等).
while (getline(FileStream, CurrentReadLine))
{
if (CurrentReadLine.find("GeneralLicense") != std::string::npos)
{
std::cout << "General License Line: " << CurrentReadLine;
}
else if (CurrentReadLine.find("License") != std::string::npos)
{
std::cout << "License Line: " << CurrentReadLine;
}
}
Run Code Online (Sandbox Code Playgroud)