使用strtok从输入字符串中获取某些字符串

时间:2013-10-18 17:06:04

标签: c++ string strtok

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”。我可以对程序做些什么改变呢?

1 个答案:

答案 0 :(得分:1)

如果您已开始使用strtok,则至少应使用其可重入版本strtok_r。然后,您应该将代码更改为在空格处分割,而不是在散列标记处。这会给你你的代币。最后,在循环中,您需要查找第一个字符作为哈希标记,如果项目存在则将项目添加到列表中,并在哈希标记不存在时忽略该项目。

更好的方法是使用字符串流:将字符串放入其中,逐个读取标记,并丢弃没有散列标记的字符串。

使用C ++ 11的lambdas,只需很少的代码就可以实现这一点:

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.