c语言

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

小亿
158
2024-08-05 19:14:11
栏目: 编程语言
C语言开发专用服务器,限时0元免费领! 查看>>

在C语言中,可以使用标准库函数strstr()来查找一个字符串中是否包含另一个字符串。strstr()函数的原型如下:

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

其中haystack是要查找的字符串,needle是要查找的子字符串。strstr()函数会返回一个指向needlehaystack中第一次出现的位置的指针,如果没有找到,则返回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) {
        printf("The substring was found at position %ld\n", result - haystack);
    } else {
        printf("The substring was not found\n");
    }

    return 0;
}

上述代码中,我们在haystack中查找needle字符串,如果找到,则打印出needle字符串在haystack中的位置,否则打印出未找到的信息。

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

相关推荐:c语言怎么在字符串中查找字符串

0
看了该问题的人还看了