温馨提示×

C++ strstr函数的正确用法

c++
小樊
82
2024-06-13 18:26:41
栏目: 编程语言

strstr函数是用于在字符串中查找指定子字符串的函数。它的原型为:

char *strstr(const char *haystack, const char *needle);

其中,haystack是要在其中搜索的字符串,needle是要搜索的子字符串。

使用strstr函数的正确用法如下:

#include <iostream>
#include <cstring>

int main() {
    const char *haystack = "Hello, world!";
    const char *needle = "world";
    
    char *result = strstr(haystack, needle);
    
    if(result) {
        std::cout << "Found at position: " << result - haystack << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }
    
    return 0;
}

上面的代码首先定义了两个字符串haystack和needle,然后调用strstr函数在haystack中查找needle字符串。如果找到了,则打印出其位置;否则打印出"Not found"。

0