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

