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; // 返回结果
        }
    }
}
相关推荐
xhyu6117 分钟前
【学习笔记】图像质量评估方法 (5.生成图像是否符合用户要求)
笔记·学习·计算机视觉
高晶31 分钟前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy34 分钟前
大数计算思路
算法
高晶44 分钟前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗1 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李1 小时前
反向传播计算梯度举例
算法
niyongsheng1 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
卿卿的产品经理日记2 小时前
【AI产品经理实战】Day 38|try-except 踩坑实录:报错是数据
人工智能·笔记·python·学习·产品经理
keyipatience2 小时前
TypeScript学习(1)
前端·javascript·学习·typescript·html·css3
302wanger2 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法