我正在嘗試迭代字符串的單詞??梢约僭O(shè)該字符串由用空格分隔的單詞組成。請注意,我對C字符串函數(shù)或那種字符操作/訪問不感興趣。另外,請在答案中優(yōu)先考慮優(yōu)雅而不是效率。我現(xiàn)在最好的解決方案是:#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);}有沒有更優(yōu)雅的方式來做到這一點?
4 回答

慕村9548890
TA貢獻1884條經(jīng)驗 獲得超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 關(guān)注
- 642 瀏覽
添加回答
舉報
0/150
提交
取消