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

   2024-09-30 7380
核心提示:在C语言中,可以使用strstr()函数在一个字符串中查找另一个字符串#includestdio.h#includestring.hint main() {char haystack[]

在C语言中,可以使用strstr()函数在一个字符串中查找另一个字符串

#include<stdio.h>#include<string.h>int main() {    char haystack[] = "Hello, welcome to the world of programming!";    char needle[] = "world";    char *result = strstr(haystack, needle);    if (result) {        printf("Found the string '%s' in the text '%s'.\n", needle, haystack);    } else {        printf("The string '%s' was not found in the text '%s'.\n", needle, haystack);    }    return 0;}

在这个示例中,我们定义了两个字符串变量haystackneedle。然后,我们使用strstr()函数在haystack中查找needle。如果找到了匹配的子字符串,strstr()函数将返回一个指向该子字符串的指针,否则返回NULL。我们使用if语句检查结果,并根据是否找到子字符串打印相应的消息。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

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