温馨提示×

c语言中的strstr函数怎么使用

小亿
85
2024-02-28 16:51:13
栏目: 编程语言

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

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

其中,haystack表示要查找的字符串,needle表示要搜索的子字符串。

使用方法如下:

#include <stdio.h>
#include <string.h>

int main() {
    const char *haystack = "Hello, world!";
    const char *needle = "world";
    
    char *result = strstr(haystack, needle);
    
    if (result) {
        printf("'%s' found at position %ld\n", needle, result - haystack);
    } else {
        printf("'%s' not found\n", needle);
    }
    
    return 0;
}

以上代码将在haystack中查找needle,如果找到则输出其位置,否则输出未找到的信息。

0