【C语言经典面试题】源码实现标准库函数strstr

【C语言经典面试题】源码实现标准库函数strstr

你有面试中,要求写strstr的源码实现吗?本文给出一个参考写法!

1 需求说明

题目大意如下:

请参考标准C库对strstr的申明定义,使用C语言的语法写出其实现源码。

2 源码实现

2.1 函数申明

通过查看man帮助,我们可以知道strstr函数的功能及其简要申明。

NAME
       strstr, strcasestr - locate a substring

SYNOPSIS
       #include <string.h>

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

       #define _GNU_SOURCE         /* See feature_test_macros(7) */

       #include <string.h>

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

DESCRIPTION
       The strstr() function finds the first occurrence of the substring needle in the string haystack.  The terminating null bytes ('\0') are not com‐
       pared.

       The strcasestr() function is like strstr(), but ignores the case of both arguments.

RETURN VALUE
       These functions return a pointer to the beginning of the located substring, or NULL if the substring is not found.

2.2 功能实现

以下是我的一个简单实现源码,仅供参考:

char *my_strstr(const char *searchee, const char *lookfor)
{
      /* Less code size, but quadratic performance in the worst case.  */
    if (*searchee == 0)
    {
        if (*lookfor)
            return (char *) NULL;
        return (char *) searchee;
    }

    while (*searchee)
    {
        size_t i;
        i = 0;

        while (1)
        {
            if (lookfor[i] == 0)
            {
                return (char *) searchee;
            }

            if (lookfor[i] != searchee[i])
            {
                break;
            }
            i++;
        }
        searchee++;
    }

    return (char *) NULL;
}

3 源码测试

简单的测试代码如下:

#include <stdio.h>
#include <assert.h>

int main(void)
{
    char str[30] = "123456789abcdef";
    
    printf("str-str1: %s\r\n", strstr(str, "678"));
    printf("str-str2: %s\r\n", my_strstr(str, "678"));

    return 0;
}

执行编译后,运行小程序的结果:

image-20221031202020106

从运行结果上看,基本满足了题目要求,有心的读者可以进一步测试其他测试用例。

4 小小总结

strstr的源码实现,核心就是字符串比较,实现的过程中,主要识别字符串的结束,以及两个字符串长度的数量关系,对结果的输出都有一定的影响。

5 更多分享

架构师李肯

架构师李肯全网同名),一个专注于嵌入式IoT领域的架构师。有着近10年的嵌入式一线开发经验,深耕IoT领域多年,熟知IoT领域的业务发展,深度掌握IoT领域的相关技术栈,包括但不限于主流RTOS内核的实现及其移植、硬件驱动移植开发、网络通讯协议开发、编译构建原理及其实现、底层汇编及编译原理、编译优化及代码重构、主流IoT云平台的对接、嵌入式IoT系统的架构设计等等。拥有多项IoT领域的发明专利,热衷于技术分享,有多年撰写技术博客的经验积累,连续多月获得RT-Thread官方技术社区原创技术博文优秀奖,荣获CSDN博客专家CSDN物联网领域优质创作者2021年度CSDN&RT-Thread技术社区之星2022年RT-Thread全球技术大会讲师RT-Thread官方嵌入式开源社区认证专家RT-Thread 2021年度论坛之星TOP4华为云云享专家(嵌入式物联网架构设计师)等荣誉。坚信【知识改变命运,技术改变世界】!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享