我正在尝试迭代字符串的单词。可以假设该字符串由用空格分隔的单词组成。请注意,我对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);}有没有更优雅的方式来做到这一点?
4 回答
慕村9548890
TA贡献1884条经验 获得超4个赞
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::string str("Split me by whitespaces");
std::string buf; // Have a buffer string
std::stringstream ss(str); // Insert the string into a stream
std::vector<std::string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
return 0;
}
- 4 回答
- 0 关注
- 617 浏览
添加回答
举报
0/150
提交
取消