温馨提示×

c语言怎么查找字符串

小亿
116
2024-01-08 16:22:10
栏目: 编程语言

在C语言中,可以使用库函数strstr来查找字符串。strstr函数的原型如下:

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

其中,haystack表示要搜索的字符串,needle表示要查找的字符串。strstr函数会在haystack中查找第一次出现needle的位置,并返回一个指向该位置的指针。如果找不到needle,则返回NULL

以下是一个示例代码:

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

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

输出结果为:

Found at position: 7

这表示在字符串"Hello, world!"中,子字符串"world"出现在位置7处。

0