2013-01-24 111 views
1

该函数浏览添加到缓冲区中的字符串并搜索指定的字段。如果在缓冲区中找到该字段,则返回指向所分配内容的指针。如果在缓冲区内找不到指定的字段,则指向“?”的指针字符串被传送。在缓冲区中查找字符串

#include <stdio.h> 
#include <string.h> 

char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30"; 

const char * get_info (const char *name) 
{ 
    unsigned nl; 
    const char *p, *e; 

    if(name!=NULL) 
    { 
     nl = strlen(name); 
     for (p = buf, e = p + strlen(buf) ; p < e && p[0] ; p += strlen(p) + 1) { 
      printf("p = %s\tname = %s\te = %s\n", p, name, e); 
      if (strncmp (p, name, nl) == 0 && p[nl] == '=') 
       return (p + nl + 1); 
     } 
    } 
    return "?"; 
} 

int main() 
{ 
    printf("strlen(buf) = %d\n", strlen(buf)); 
    printf("%s\n", get_info("Nath")); 
    return 0; 
} 

执行后,我总是得到?作为输出,代码有什么问题?另外请注意,在上面的代码中用sizeof代替strlen是否可取? sizeof(buf)返回256

[email protected]:~/programs/test$ ./a.out 
strlen(buf) = 21 
p = Manavendra Nath Manav  name = Nath  e = 
? 

编辑:对不起,我没有更新大约p[nl] == '='之前。如果缓冲区类似于 char buf[256] = "ID=1234 Name=Manavendra Nath Manav Age=30";get_info("Name")应返回Manavendra Nath Manav

+0

从你的描述,这听起来像你只是想编写[的strstr(HTTP:// en.cppreference.com/w/c/string/byte/strstr),但这不是你的代码所做的。你能证明你的结果是什么吗? – Useless

+0

是否允许使用C++? – TemplateRex

回答

0

return内循环,如果p[nl]等于'='只能执行:

 if (strncmp (p, name, nl) == 0 && p[nl] == '=') 
             ^^^^^^^^^^^^^^^ 

不过,也有在你的字符串没有'=',所以它总是被执行的最后return "?"

0

这可能不是问题的确切答案,但逻辑看起来相当复杂。你能不能substr()来解决问题。此外1级的错误,我能找到如果(STRNCMP(P,名称,NL)== 0 & & P [NL] == '=')P [NL] == '='永远不会为真。

0

我觉得这是你要找的行为:

#include <string> 

const char * get_info_2(const char * name){ 
    std::string str_1(buf); 
    std::string str_2(name); 
    for (unsigned int i = 0; i < str_1.size() - str_2.size(); ++i){ 
    if (str_1.substr(i,str_2.size()).compare(str_2) == 0){ 
     return str_1.substr(i,str_2.size()).c_str(); 
    } 
    } 
    return "?"; 
} 
0

你为什么要为共同的东西作为字符串匹配编写自己的代码? STL中有几种方法可以做到这一点,最简单的是用std::string

#include <iostream> 
#include <string> 

char buf[256] = "Manavendra Nath Manav"; 
char sub[256] = "Nath"; 

int main() 
{ 
    std::string bufs(buf); 
    std::string subs(sub); 

    auto pos = bufs.find(sub); 
    if (pos != std::string::npos) 
     std::cout << bufs.substr(pos, subs.length()) << "\n"; 
    else 
     std::cout << "?\n"; 
} 

输出上LiveWorkSpace

+0

嗯他标记它C –

+0

@Claptrap原贴标签为C++,其他人删除了。 – TemplateRex