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;
我想编写一个程序,将所有散列标签单词存储在一个字符串 vector 中。上面的程序在第一个索引中存储了“hello junk”而不是“hello”。我可以对程序进行哪些更改以使其这样做?
最佳答案
如果您打算使用 strtok
,您至少应该使用它的可重入版本 strtok_r
。然后,您应该更改代码以按空格而不是散列标记进行拆分。这会给你 token 。最后,在循环中,您需要查找第一个字符作为散列标记,如果存在则将该项目添加到列表中,如果散列标记不存在则忽略该项目。
更好的方法是使用字符串流:将字符串放入其中,一个一个地读取标记,并丢弃没有散列标记的标记。
以下是如何使用 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] == '#'; } );
关于c++ - 使用 strtok 从输入字符串中获取某些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455249/