当前位置:编程学习 > C/C++ >>

函数memstr

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

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

 


[cpp]
//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; 

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

 

 

 

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,