简介
查找文本文件中字符串是否存在
代码
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
bool SearchString(string filePath, string strF)
{
vector<string> lines;
string line;
ifstream file(filePath); // 打开文件 example.txt
if (file.is_open()) // 判断文件是否打开成功
{
while (getline(file, line)) // 逐行读取文件内容
lines.push_back(line); // 将每行数据存入 vector 中
file.close(); // 关闭文件
}
if (find(lines.begin(), lines.end(), strF) == lines.end())
{
return false;
}
else
{
return true;
}
}
int main()
{
string filePath = "F:\\lihai.txt";
string searchString1 = "梅须逊雪三分白";
string searchString2 = "何曾吹落北风中";
bool result1 = SearchString(filePath, searchString1);
bool result2 = SearchString(filePath, searchString2);
cout << "Search result for \"" << searchString1 << "\":" << endl;
cout << (result1 ? "Found" : "Not found") << endl;
cout << "Search result for \"" << searchString2 << "\":" << endl;
cout << (result2 ? "Found" : "Not found") << endl;
cin.get();
return 0;
}
输出:
Search result for “梅须逊雪三分白”:
Not found
Search result for “何曾吹落北风中”:
Found