C ++中的strstr()
该strstr()函数是string.h中的预定义函数。它用于查找字符串中子字符串的出现。匹配过程在“\0”处停止,不包括在内。
的语法strstr()如下-
char *strstr( const char *str1, const char *str2)
在上面的语法中,strstr()找到字符串str1中字符串str2的第一个出现。实现的程序strstr()如下-
示例
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char str1[] = "Apples are red";
char str2[] = "are";
char *ptr;
ptr = strstr(str1, str2);
if(ptr)
cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1;
else
cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;
return 0;
}输出结果
上面程序的输出如下-
Occurance of "are" in "Apples are red" is at position 8
在上面的程序中,str1和str2分别定义为值“Apples红色”和“are”。这在下面给出-
char str1[] = "Apples are red"; char str2[] = "are"; char *ptr;
指针ptr指向“苹果红色”中首次出现“are”。这是通过strstr()方法完成的。下面的代码片段如下-
ptr = strstr(str1, str2);
如果指针ptr包含一个值,则显示str2在str1中的位置。否则,显示在ptr1中没有出现ptr2。这如下所示-
if(ptr) cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1; else cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;