回答

收藏

如何迭代字符串的单词?

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

我正在尝试遍历字符串的单词。
' k' }# w3 Q& `9 G3 }假设字符串由空格分隔的单词组成。& I7 B- \( _9 c" Z% g: y
请注意,我对 C 字符串函数或字符操作/访问不感兴趣。此外,请优先考虑优雅而不是效率。
* u) y, }3 q4 Q- U我现在最好的解决办法是:2 I$ B: h% J- ]# k* m1 _1 Z

    # s7 {* j: D5 B" U2 a2 _
  • #include #include #include using namespace std;int main(){    string s = "Somewhere down the road";    istringstream iss(s);    do                                                                                                                                                                                                                 string subs;        iss >> subs;        cout 有没有更优雅的方法来做到这一点?
    1 c' n" I2 E* ^) \9 m# M' j
  •                                                                " T% ]' R: u9 F+ c$ G
  •     解决方案:                                                               
    ; b) Z/ ^+ x; ]
  •                                                                 我用它来分隔字符串。第一个将结果放入预先构建的向量中,第二个返回新向量。[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;}
    + {4 ?5 E: N9 I) Q# b4 q( U7 \
请注意,此解决方案不会跳过空标记,因此以下将找到 4 项,其中一项为空:
8 l% \% ]1 j9 E% A[code]std::vector x = split("one:two::three",code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则