函数memstr

15 篇文章 0 订阅
7 篇文章 0 订阅

大家用了memchr、strchr、strstr之后,有没有想要一个叫memstr的函数?从内存里面找特定的字符串?

glibc里面没有提供memstr,我这里提供一个吧。验证过的可靠版本:


//find 'substr' from a fixed-length buffer 
//('full_data' will be treated as binary data buffer)
//return NULL if not found
char* memstr(char* full_data, int full_data_len, char* substr)
{
    if (full_data == NULL || full_data_len <= 0 || substr == NULL) {
        return NULL;
    }

    if (*substr == '\0') {
        return NULL;
    }

    int sublen = strlen(substr);

    int i;
    char* cur = full_data;
    int last_possible = full_data_len - sublen + 1;
    for (i = 0; i < last_possible; i++) {
        if (*cur == *substr) {
            //assert(full_data_len - i >= sublen);
            if (memcmp(cur, substr, sublen) == 0) {
                //found
                return cur;
            }
        }
        cur++;
    }

    return NULL;
}

这个函数调用了memcmp,应该可以利用memcmp的加速能力。


ps:研究过memcmp的同学应该都知道,memcmp会针对硬件做优化,比如一次比较多个字节什么的。



  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值