c++

c++中strstr函数的用法是什么

小亿
160
2024-02-22 11:24:27
栏目: 编程语言

在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

0
看了该问题的人还看了