2013-01-24 113 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