我正在尝试迭代字符串的单词.
可以假设该字符串由用空格分隔的单词组成.
请注意,我对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);
}
Run Code Online (Sandbox Code Playgroud)
有没有更优雅的方式来做到这一点?
可能重复:
如何在C++中拆分字符串?
在C++中拆分字符串的最佳方法?可以假设该字符串由分隔的字组成;
从我们的指南角度来看,不允许使用C字符串函数,也不允许使用Boost,因为不允许使用安全锥形开源.
我现在最好的解决方案是:
string str("denmark; sweden; india; us");
str上面应该作为字符串存储在vector中.我们怎样才能做到这一点?
感谢您的投入.