用 char *strstr() 函数 ,std::c_str()函数
strstr, wcsstr, _mbsstr
Find a substring.
char *strstr( const char *string, const char *strCharSet );
wchar_t *wcsstr( const wchar_t *string, const wchar_t *strCharSet );
unsigned char *_mbsstr( const unsigned char *string, const unsigned char *strCharSet );
| Routine | Required Header | Compatibility |
| strstr | <string.h> | ANSI, Win 95, Win NT |
| wcsstr | <string.h> or <wchar.h> | ANSI, Win 95, Win NT |
| _mbsstr | <mbstring.h> | Win 95, Win NT |
For additional compatibility information, see Compatibility in the Introduction.
Libraries
| LIBC.LIB | Single thread static library, retail version |
| LIBCMT.LIB | Multithread static library, retail version |
| MSVCRT.LIB | Import library for MSVCRT.DLL, retail version |
Return Value
Each of these functions returns a pointer to the first occurrence of strCharSet in string, or NULL if strCharSet does not appear in string. If strCharSet points to a string of zero length, the function returns string.
Parameters
string
Null-terminated string to search
strCharSet
Null-terminated string to search for
Remarks
The strstr function returns a pointer to the first occurrence of strCharSet in string. The search does not include terminating null characters. wcsstr and _mbsstr are wide-character and multibyte-character versions of strstr. The arguments and return value of wcsstr are wide-character strings; those of _mbsstr are multibyte-character strings. These three functions behave identically otherwise.
basic_string::c_str
const E *c_str() const;
The member function returns a pointer to a nonmodifiable C string constructed by adding a terminating null element (E(0)) to the controlled sequence. Calling any non-const member function for *this can invalidate the pointer.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string p,s;
cin>>s;
int n;
cin>>n;
const char *temp;
for(int i=0;i<n;i++)
{
cin>>p;
temp=strstr( s.c_str(),p.c_str() );
if( temp )
cout<<temp<<endl;
else
cout<<"Not Found"<<endl;
}
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string p,s;
cin>>s;
int n;
cin>>n;
const char *temp;
for(int i=0;i<n;i++)
{
cin>>p;
temp=strstr( s.c_str(),p.c_str() );
if( temp )
cout<<temp<<endl;
else
cout<<"Not Found"<<endl;
}
return 0;
}
本文介绍如何使用strstr函数在C/C++中查找子字符串,并提供了一个示例程序,该程序读取主字符串和要搜索的多个子字符串,如果找到匹配项则输出匹配的位置。

被折叠的 条评论
为什么被折叠?



