如何在C++中搜索关键字?写一个程序?

2025-02-27 10:09:58
推荐回答(2个)
回答1:

1、可以通过string::find方法查找关键字:
原型:size_t find (const string& str, size_t pos = 0) const;

2、示例:

string s = "c++面向对象程序设计教程";
if(s.find("面向对象") != string::npos){
cout << "FOUND";
}

回答2:

#include
#include
#include
using namespace std ;

int main()
{
ifstream infile ;
char filename[100];
string str ;
string key ;

cout << "input key word: " ;
cin >> key ;
for( int i=10001 ;i<=10003;i++ )
{
sprintf(filename,"%d", i );
infile.open( filename );
if ( infile.good() )
{
while( infile >> str )
{
if ( str==key )
{
cout << filename < return 0;
}
}
infile.close();
}
}
cout << "no match!" < return -1;
}