Day30~实现strcmp、strncmp、strchr、strpbrk

实现strcmp、strncmp、strchr、strpbrk

cpp 复制代码
int my_strcmp(char *s1, char *s2)
{
    if (s1 == NULL && s2 == NULL)
    {
        return 0;
    }
    if (s1 != NULL && s2 == NULL)
    {
        return 1;
    }
    if (s1 == NULL && s2 != NULL)
    {
        return -1;
    }

    while (*s1 != '\0' && *s2 != '\0')
    {
        if (*s1 > *s2)
        {
            return 1;
        }
        else if (*s1 < *s2)
        {
            return -1;
        }
        s1++;
        s2++;
    }

    if (*s1 == '\0' && *s2 == '\0')
    {
        return 0;
    }
    if (*s1 != '\0' && *s2 == '\0')
    {
        return 1;
    }
    if (*s1 == '\0' && *s2 != '\0')
    {
        return -1;
    }
}

int my_strncmp(char *s1, char *s2, size_t n)
{
    if (s1 == NULL || s2 == NULL)
    {
        return -1;
    }

    for (int i = 0; (i < n && (*s1 != '\0' && *s2 != '\0')); i++)
    {
        if (s1[i] != s2[i])
        {
            return -1;
        }
    }
    return 0;
}

char *my_strchr(char *s, int c)
{
    while (*s != '\0')
    {
        if (*s == c)
        {
            return s;
        }
        else
        {
            s++;
        }
    }
}

char *my_strpbrk(char *s, char *accept)
{
    char *temp = accept;
    char *result = NULL;

    while (*accept != '\0')
    {
        temp = strchr(s, *accept); // 查找accept第一次在字符s中出现的位置
        if (temp != NULL)          // 如果找到
        {
            result = temp;          // 将第一次找到的位置赋值给result
            while (*accept != '\0') // 再次遍历
            {
                temp = strchr(s, *accept);         // 再次查找
                if (temp != NULL && temp < result) // 如果找到且比第一次找到的位置更靠左,则取
                {
                    result = temp; // 赋值给result
                }
                accept++; // 指针后移
            }
            return result; // 返回结果
        }
    }
}
相关推荐
辰海Coding2 小时前
MiniSpring框架学习笔记-解决循环依赖的简化IoC容器
笔记·学习
晓梦林3 小时前
cp520靶场学习笔记
android·笔记·学习
心中有国也有家4 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
Upsy-Daisy4 小时前
AI Agent 项目学习笔记(八):Tool Calling 工具调用机制总览
人工智能·笔记·学习
绝知此事4 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院4 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet5 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
LuminousCPP5 小时前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习
魔法阵维护师5 小时前
从零开发游戏需要学习的c#模块,第十四章(保存和加载)
学习·游戏·c#