回答

收藏

如何迭代字符串的单词?

技术问答 技术问答 321 人阅读 | 0 人回复 | 2023-09-11

我正在尝试遍历字符串的单词。
3 H2 }4 T9 b% O; R- d8 `1 j5 V假设字符串由空格分隔的单词组成。! Z/ E) B% c# z4 o6 _' M. ?* \
请注意,我对 C 字符串函数或字符操作/访问不感兴趣。此外,请优先考虑优雅而不是效率。9 P+ f- @+ Z  _8 M. ~2 l* D" t3 j
我现在最好的解决办法是:( P8 O6 i! C) U3 y8 M$ ~. |; W0 r

    : P* |* ~2 R- g2 Y3 v
  • #include #include #include using namespace std;int main(){    string s = "Somewhere down the road";    istringstream iss(s);    do                                                                                                                                                                                                                 string subs;        iss >> subs;        cout 有没有更优雅的方法来做到这一点?; `) Y: w- h: y4 W) u* J( Y
  •                                                                6 T1 h. x" d* y/ S
  •     解决方案:                                                               : W+ @* G, y; V3 r+ g
  •                                                                 我用它来分隔字符串。第一个将结果放入预先构建的向量中,第二个返回新向量。[code]#include #include #include #include template void split(const std::string &s,char delim,Out result)    std::istringstream iss(s);    std::string item;    while (std::getline(iss,item,delim))        *result   = item;   std::vector split(const std::string &s,char delim)    std::vector elems;    split(s,delim,std::back_inserter(elems));    return elems;}: e7 O) M  G; k! c; J" \
请注意,此解决方案不会跳过空标记,因此以下将找到 4 项,其中一项为空:
8 Y0 X% N5 a' ]% b+ V" E9 }[code]std::vector x = split("one:two::three",code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则