在C++中,strstr
函数用于在一个字符串中搜索指定子字符串的位置。其原型如下:
char*strstr(constchar*str1,constchar*str2);
其中,str1
是要搜索的字符串,str2
是要查找的子字符串。strstr
函数会返回指向第一次出现str2
的位置的指针,如果找不到则返回nullptr
。
示例代码:
#include<iostream>
#include<cstring>
intmain(){
constchar*str1="Hello,world!";
constchar*str2="world";
char*result=strstr(str1,str2);
if(result){
std::cout<<"Foundatposition:"<<result-str1<<std::endl;
}else{
std::cout<<"Notfound"<<std::endl;
}
return0;
}
输出结果为:
Foundatposition:7