函数memstr

大家用了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会针对硬件做优化,比如一次比较多个字节什么的。



posted on 2013-04-12 10:09  如果蜗牛有爱情  阅读(1011)  评论(0编辑  收藏  举报

导航