C语言实现库函数汇总

通过实现库函数提高库函数的理解和算法能力。

一、字符串

1. strstr子串查找

  1. 实现 strStr()

给定一个 haystack 字符串和一个 needle 字符串,
在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

int strstr_my(const char *haystack, const char *needle)
{
    int len1 = strlen(haystack);
    int len2 = strlen(needle);
    if (len2 < 1) {
        return 0;
    }
    int i = 0;
    int temp1, temp2;
    for (i = 0; i < len1; i++) {
        if (len1 - i < len2) {
            return -1;
        }
        temp1 = i;
        temp2 = 0;
        while (haystack[temp1++] == needle[temp2++]) {
            if (temp2 == len2) {
                return i;
            }
        }
    }
    return -1;
}

作者:yusq77

-------------------------------------------

Wish you all the best and good health in 2021.

原文地址:https://www.cnblogs.com/yusq77/p/13674508.html