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; // 返回结果
        }
    }
}
相关推荐
blanks20201 小时前
c 语言基础 二级指针理解
c
AvocadoZeroOneOI3 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
Z21-X4 小时前
云原生运维学习笔记:Kubernetes Volume 与 Secret 实验
运维·笔记·学习·云原生·kubernetes
cjz38995 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
console.log('npc')8 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子139 小时前
【高级数据库】关系代数基本概念
算法
星落梦生10 小时前
Docker学习(11)
学习·docker·容器
电科_银尘20 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl