Hello, 大家好,我是爱吃香蕉的猴子,C++中字符串匹配
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "aa.txt";
//以读模式打开文件
ifstream fin(filename.c_str());
//判断打开状态
if (fin.is_open()){
printf("open file success");
} else {
printf("open file fail");
return 0;
}
int index = 0;
string strline;
while (getline(fin, strline) && index < 5)
{
bool exists = strline.find("context") == string::npos;
if (exists)
{
printf("ok");
}
else
{
printf("not ok");
}
cout << strline << '\t' << !exists << endl;
index++;
}
fin.close();
cout << "Done!\n";
return 0;
}
int readFile(std::string path, string str)
{
//以读模式打开文件
ifstream fin(path.c_str());
//c_str():生成一个const char*指针,指向以空字符终止的数组
//判断打开状态
if (!fin.is_open()) {
printf("open file fail");
return 0;
}
int index = 0;
string strline;
while (getline(fin, strline) && index < 5)
{
//find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos
bool exists = strline.find(str) == string::npos;
if (exists)
{
printf("ok");
}
else
{
printf("not ok");
}
cout << strline << '\t' << !exists << endl;
index++;
}
fin.close();
return 0;
}
Code的搬运工V1.0