溫馨提示×

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

小億
110
2024-08-05 19:14:11
欄目: 編程語言

在C語言中,可以使用標(biāo)準(zhǔn)庫函數(shù)strstr()來查找一個字符串中是否包含另一個字符串。strstr()函數(shù)的原型如下:

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

其中haystack是要查找的字符串,needle是要查找的子字符串。strstr()函數(shù)會返回一個指向needlehaystack中第一次出現(xiàn)的位置的指針,如果沒有找到,則返回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中的位置,否則打印出未找到的信息。

0