温馨提示×

c语言strstr函数的作用是什么

小亿
90
2024-02-22 11:29:25
栏目: 编程语言

在C语言中,strstr函数用于在一个字符串中查找另一个字符串第一次出现的位置。该函数的原型如下:

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

其中,haystack是要查找的字符串,needle是要查找的子字符串。该函数会返回一个指向第一次出现needle的位置的指针,如果未找到则返回NULL。

例如,如果有字符串"hello world",要查找其中是否包含字符串"world",可以使用strstr函数:

char *result = strstr("hello world", "world");
if (result != NULL) {
    printf("Found at position: %ld\n", result - "hello world");
}

上述代码会输出Found at position: 6,表示在字符串"hello world"中找到了子字符串"world",并且是从位置6开始的。

0