c语言怎么查找字符串

583
2023/12/10 16:22:10
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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处。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言中字符串长度怎么算