C语言重写strncpy()、strcmp()、strchr()、atoi()函数

重写strncpy()函数

char* repeat_strncpy(char* s, int n)
{
    int len = strlen(s);    // 目标:拷贝s的n个字符出去
                            // 但是len可能比n小
                            // 此时,需要把n重新赋值为len
    int copyCount = len < n ? len : n;
    char* ptr = s;
    char* p = new char[copyCount+1];
    // ver3 by wdz
    while (ptr - s < copyCount)  // 利用指针偏移量进行循环;
    {
        *p++ = *ptr++;
    }
    *p = '\0';

    return p - copyCount;    // 注意指针偏移到数组末端,需要返回到起始位置再return;
}

重写strcmp()函数,并返回目标字符串首地址

//若“at”在“hats”内,则返回"hats"中a的地址;
const char* string_in(const char* s1, const char* s2)
{
    if (!s1 || !s2)
        return NULL;

    const char* n = s1; // 下一个查找位置

    while (*n)
    {
        // 先找到第一个相等的
        const char* f = n;
        while (*f != *s2 && *f != '\0')
        {
            ++f;
        }

        if (*f == '\0')
        {
            // 到了结尾也没找到啊!
            return NULL;
        }
        else
        {
            // 可能就要找到了
            // 先确定下一次查找的起始位置
            n = f + 1;

            // 继续进行本次查找比较
            // 看看能否完成全部匹配
            const char* q = s2;
            while (*q)
            {
                if (*f != *q)
                {
                    // a!失败了
                    // 继续查找下一个吧
                    break;
                }
                ++f;
                ++q;
            }

            if (!*q)
            {
                // 找到了!
                return n - 1;
            }
        }
    }
}

重写strchr()函数

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

    return NULL;
}

重写atoi()函数

int repeat_atoi(char* s)
{
    char* ptr = s;
    int i = 0, n = 0, sign = 1;

    for (i = 0; isspace(ptr[i]); i++)         //跳过空白符;
        ;

    if (ptr[i] == '+' || ptr[i] == '-')        //跳过符号
    {
        sign = (ptr[i] == '-') ? -1 : 1;
            i++;
    }

    for (n = 0; isdigit(ptr[i]); i++)
        n = 10 * n + (ptr[i] - '0');          //将数字字符转换成整形数字

    return sign * n;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值