如何迭代字符串的单词?

我正在尝试迭代字符串的单词。

可以假设该字符串由用空格分隔的单词组成。

请注意,我对C字符串函数或那种字符操作/访问不感兴趣。另外,请在答案中优先考虑优雅而不是效率。

我现在最好的解决方案是:

#include <iostream>#include <sstream>#include <string>using namespace std;int main(){
    string s = "Somewhere down the road";
    istringstream iss(s);

    do
    {
        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);}

有没有更优雅的方式来做到这一点?


芜湖不芜
浏览 618回答 4
4回答

慕村9548890

#include <vector>#include <string>#include <sstream>int main(){&nbsp; &nbsp; std::string str("Split me by whitespaces");&nbsp; &nbsp; std::string buf;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Have a buffer string&nbsp; &nbsp; std::stringstream ss(str);&nbsp; &nbsp; &nbsp; &nbsp;// Insert the string into a stream&nbsp; &nbsp; std::vector<std::string> tokens; // Create vector to hold our words&nbsp; &nbsp; while (ss >> buf)&nbsp; &nbsp; &nbsp; &nbsp; tokens.push_back(buf);&nbsp; &nbsp; return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP