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

标签 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;

我想编写一个程序,将所有散列标签单词存储在一个字符串 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] == '#'; } );

Demo on ideone.

关于c++ - 使用 strtok 从输入字符串中获取某些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455249/

相关文章:

c++ - cout long double 问题

r - 将字符串分成字符

c - 使用 strtok() 在 c 中将字符串标记两次

c - strtok_r() 是否是 string.h 的一部分

c++ - 编译器在 strstok() (C++) 之后不继续

c++ - 自定义预期失败的完整错误消息 (boost::spirit::x3)

c++ - 整数数组到 vector

c++ - 本地的对象生命周期被放入一个新的数组中

jquery - 检索 jQuery 选择器的字符串表示形式

c# - 如何从 C# 中的字符串中提取 href 标签?