回答

收藏

如何迭代字符串的单词?

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

我正在尝试遍历字符串的单词。- V" G" s3 R( Q6 ~
假设字符串由空格分隔的单词组成。9 ^/ _2 W6 F! m! ?" D  G2 G4 \
请注意,我对 C 字符串函数或字符操作/访问不感兴趣。此外,请优先考虑优雅而不是效率。: q9 m8 `! Q( `
我现在最好的解决办法是:9 l4 Y/ v$ G' L- c" T7 e9 d
    / a0 `; c4 X4 b, Z) S
  • #include #include #include using namespace std;int main(){    string s = "Somewhere down the road";    istringstream iss(s);    do                                                                                                                                                                                                                 string subs;        iss >> subs;        cout 有没有更优雅的方法来做到这一点?  C2 x, ~- w4 e
  •                                                                , v6 q. m8 z. J; w5 u3 X
  •     解决方案:                                                               
    : m8 K8 k5 f8 M
  •                                                                 我用它来分隔字符串。第一个将结果放入预先构建的向量中,第二个返回新向量。[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;}  k2 s' N+ D- l
请注意,此解决方案不会跳过空标记,因此以下将找到 4 项,其中一项为空:+ c' W, W6 T! s& e
[code]std::vector x = split("one:two::three",code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则