如何迭代由空格分隔的单词组成的字符串中的单词?
注意,我对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);
}
这是我写的一个函数,帮助我做了很多事情。它在为WebSocket做协议时帮助了我。
using namespace std;
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
vector<string> split ( string input , string split_id ) {
vector<string> result;
int i = 0;
bool add;
string temp;
stringstream ss;
size_t found;
string real;
int r = 0;
while ( i != input.length() ) {
add = false;
ss << input.at(i);
temp = ss.str();
found = temp.find(split_id);
if ( found != string::npos ) {
add = true;
real.append ( temp , 0 , found );
} else if ( r > 0 && ( i+1 ) == input.length() ) {
add = true;
real.append ( temp , 0 , found );
}
if ( add ) {
result.push_back(real);
ss.str(string());
ss.clear();
temp.clear();
real.clear();
r = 0;
}
i++;
r++;
}
return result;
}
int main() {
string s = "S,o,m,e,w,h,e,r,e, down the road \n In a really big C++ house. \n Lives a little old lady. \n That no one ever knew. \n She comes outside. \n In the very hot sun. \n\n\n\n\n\n\n\n And throws C++ at us. \n The End. FIN.";
vector < string > Token;
Token = split ( s , "," );
for ( int i = 0 ; i < Token.size(); i++) cout << Token.at(i) << endl;
cout << endl << Token.size();
int a;
cin >> a;
return a;
}