2013-10-18 44 views
0
vector<string> CategoryWithoutHashTags; 
string tester = "#hello junk #world something #cool"; 
char *pch; 
char *str; 
str = new char [tester.size()+1]; 
strcpy(str, tester.c_str()); 

pch = strtok(str,"#"); 
while(pch!=NULL) 
{ 
    CategoryWithoutHashTags.push_back(pch); 
    pch=strtok(NULL,"#"); 
} 
cout<<CategoryWithoutHashTags[0]<<endl; 

我想寫一個程序,它涉及將所有散列標籤字存儲在一個字符串向量中。上述程序在第一個索引中存儲「hello junk」,而不是「hello」。我可以對程序做出什麼改變來實現它?使用strtok從輸入字符串中獲取某些字符串

+2

請如果你要處理的字符串作爲不使用'strtok' –

+2

字,請使用空格作爲分隔符,而不是'#'。然後看看第一個字符,看看它是否是一個哈希標籤。 – Barmar

+2

'strtok'在多線程應用程序中特別危險。 – deepmax

回答

1

如果您使用strtok設置,至少應該使用其可重入版本strtok_r。然後,您應該將代碼更改爲在空格處拆分,而不是在散列標記處。這會給你的令牌。最後,在循環中,您需要查找第一個字符作爲哈希標記,如果該項目存在,則將該項目添加到列表中,並在哈希標記不存在時忽略該項目。

更好的方法是使用字符串流:將字符串放入它中,逐個讀取令牌,並丟棄沒有散列標記的字符串。

這裏是如何使用C++ 11的lambda表達式用很少的代碼做到這一點:

stringstream iss("#hello junk #world something #cool"); 
istream_iterator<string> eos; 
istream_iterator<string> iit(iss); 
vector<string> res; 
back_insert_iterator< vector<string> > back_ins(res); 
copy_if(iit, eos, back_ins, [](const string s) { return s[0] == '#'; }); 

Demo on ideone.