c语言怎么在字符串中查找指定字符串

   2024-10-22 5500
核心提示:在C语言中,可以使用strstr()函数来在一个字符串中查找另一个字符串。该函数的原型为:char *strstr(const char *haystack, cons

在C语言中,可以使用strstr()函数来在一个字符串中查找另一个字符串。该函数的原型为:

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

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

下面是一个示例代码:

#include <stdio.h>#include <string.h>int main() {    char str1[] = "Hello, world!";    char str2[] = "world";    char *ptr = strstr(str1, str2);    if (ptr) {        printf("'%s' found at position %ld\n", str2, ptr - str1);    } else {        printf("'%s' not found\n", str2);    }    return 0;}

运行结果为:

'world' found at position 7

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号