c语言

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

小亿
345
2024-04-12 11:43:55
栏目: 编程语言

在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

0
看了该问题的人还看了