#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s) {
string rs ;
for(int i = s.length()-1; i >= 0; ){
while(s[i] == ' ' && i >= 0)
i--;
if(i < 0){
break;
}
if(!rs.empty())
rs.push_back(' ');
string t;
while(s[i] != ' ' && i>=0)
t.push_back(s[i--]);
reverse(t.begin(),t.end());
rs.append(t);
}
s = rs;
}
int main(int argc, char** argv) {
string s = "a b cd";
reverseWords(s);
cout<<s;
return 0;
}
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s) {
string rs ;
for(int i = s.length()-1; i >= 0; ){
while(s[i] == ' ' && i >= 0)
i--;
if(i < 0){
break;
}
if(!rs.empty())
rs.push_back(' ');
string t;
while(s[i] != ' ' && i>=0)
t.push_back(s[i--]);
reverse(t.begin(),t.end());
rs.append(t);
}
s = rs;
}
int main(int argc, char** argv) {
string s = "a b cd";
reverseWords(s);
cout<<s;
return 0;
}
其他版本还有C的:
#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
void reverseWords(string &s) {
const char * src = s.c_str();
if(src == NULL)
return;
int len = 0;
bool flag = false;
while(src[len] != '