String 字符串操作函数

1. 字符串操作函数 #include <string.h>

2. 计算字符串长度 int strlen(const char *s)

int strlen(const char *s)
{
    const char *sc;

    for (sc = s; *sc != '\0'; ++sc)
    {
        // TODO, do nothing
    }

    return (sc - s);
}

2. compare 字符串对比 int strcmp(const char *cs, const char *ct)

int strcmp(const char *cs, const char *ct)
{
    signed char __res;

    while (1) {
        if (((__res = *cs - *ct++) != 0) || (!*cs++)) {
            break;
        }
    }

    return __res;
}

3. n compare 字符串对比n 个字符 int strcmp(const char *cs, const char *ct)

int strncmp(const char *cs, const char *ct, int count)
{
    signed char __res = 0;

    while (count) {
        if ((__res = *cs - *ct++) != 0 || !*cs++) {
            break;
        }
        count--;
    }

    return __res;
}

4. 内存清除,一般用于数组的清零操作

void *memset(void *s, int c, int count)
{
    char *xs = s;

    while (count--) {
        *xs++ = c;
    }

    return s;
}

5. 内存拷贝,一般用于内存块的传递,任务之间传递消息块,类似送快递

void *memcpy(void *dest, const void *src, int count)
{
    char *tmp = dest;
    const char *s = src;

    while (count--) {
        *tmp++ = *s++;
    }

    return dest;
}

6. 内存比较

int memcmp(const void *cs, const void *ct, int count)
{
    const unsigned char *su1, *su2;
    int res = 0;

    for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--) {
        if ((res = *su1 - *su2) != 0) {
            break;
        }
    }

    return res; // res = abs(cs - ct)
}

7. 内存移动

void *memmove(void *dst, const void *src, int count)
{
    char *_dst = dst;
    const char *_src = src;

    if (dst == src) {
        return dst;
    }

    if (dst < src) {
        return memcpy(dst, src, count);
    }

    _dst += count;
    _src += count;

    while(count--) {
        *--_dst = *--_src;
    }

    return dst;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值