温馨提示×

strstr函数如何实现子串查找

小樊
85
2024-06-18 12:40:59
栏目: 编程语言

在C语言中,可以通过循环遍历主串中每个字符,并使用strncmp函数来比较子串和主串中的每个可能的子串,如果相等则返回该子串在主串中的位置。具体实现可以参考以下代码:

#include <stdio.h>
#include <string.h>

char* strstr_custom(const char* haystack, const char* needle) {
    if (*needle == '\0') {
        return haystack; // 如果子串为空,则直接返回主串
    }

    while (*haystack != '\0') {
        if (*haystack == *needle && strncmp(haystack, needle, strlen(needle)) == 0) {
            return (char*) haystack; // 如果找到子串,则返回该子串在主串中的位置
        }
        haystack++;
    }

    return NULL; // 如果找不到子串,则返回NULL
}

int main() {
    const char* haystack = "hello world";
    const char* needle = "world";

    char* result = strstr_custom(haystack, needle);

    if (result != NULL) {
        printf("子串 \"%s\" 在主串 \"%s\" 中的位置为 %ld\n", needle, haystack, result - haystack);
    } else {
        printf("子串 \"%s\" 未在主串 \"%s\" 中找到\n", needle, haystack);
    }

    return 0;
}

以上代码中定义了一个自定义的strstr函数strstr_custom来实现子串查找功能。在main函数中调用strstr_custom函数来查找子串在主串中的位置,并输出结果。

0