温馨提示×

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

小亿
81
2024-09-05 06:19:49
栏目: 编程语言

在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语句检查结果,并根据是否找到子字符串打印相应的消息。

0