c语言怎么查找字符串

   2025-02-13 9210
核心提示:在C语言中,可以使用库函数strstr来查找字符串。strstr函数的原型如下:char *strstr(const char *haystack, const char *needle

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言