2011-08-27 90 views
0

好的,所以我需要解析一些信息,我想知道什麼是最好的方法來做到這一點。 好的,這裏是我需要解析的字符串。分號是「^」用C++中的分隔符解析字符串

John Doe^Male^20 

我需要將字符串解析爲姓名,性別和年齡變量。 C++中最好的方法是什麼?我正在考慮循環,並將條件設置爲while(!string.empty() ,然後將所有字符分配到字符串'^',然後清除我已分配的內容。有沒有更好的方法來做到這一點?

+5

可能的重複:http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c –

回答

2

您可以在C++流中使用getline。

istream的&函數getline(istream的&是,串&海峽,字符分隔符=」 \ n」)

改變分隔符 '^'

1

您有幾種選擇。如果可以使用boost,一個很好的選擇是它們在字符串庫中提供的分割算法。你可以看看這個使問題在行動中看到的升壓答案:How to split a string in c

如果你不能使用boost,您可以使用string::find得到一個字符的索引:

string str = "John Doe^Male^20"; 

int last = 0; 
int cPos = -1; 
while ((cPos = str.find('^', cPos + 1)) != string::npos) 
{ 
    string sub = str.substr(last, cPos - last); 

    // Do something with the string 

    last = cPos + 1; 
} 
0
#include <stdio.h> 

#include <string.h> 

int main() 

{ 

    char str[] = "This is a sample string"; 

    char * pch; 

    printf ("Looking for the 's' character in \"%s\"...\n",str); 

    pch=strchr(str,'s'); 

    while (pch!=NULL) 

    { 

    printf ("found at %d\n",pch-str+1); 

    pch=strchr(pch+1,'s'); 

    } 

    return 0; 

} 

做些什麼像這樣在一個數組中。

0

你有很多選擇,但我會使用strtok(),我自己。這將會使這項工作變短。