2013-10-18 43 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.