Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Last active December 25, 2015 09:19
Show Gist options
  • Save ravichandrae/6952899 to your computer and use it in GitHub Desktop.
Save ravichandrae/6952899 to your computer and use it in GitHub Desktop.
This program reverses the words in the given string.
#include < iostream > #include < string > #include < algorithm >
using namespace std;
void reverseWords(string & str) {
//reverse the entire string
reverse(str.begin(), str.end());
string::iterator strIt;
string::iterator wordBegin = str.begin();
//state = 0 indicates word has ended; 1 indicates scanning word
int state = 0;
for (strIt = str.begin(); strIt != str.end(); ++strIt) {
if ( * strIt == ' ') {
state = 0;
if (strIt > wordBegin) reverse(wordBegin, strIt);
} else {
if (state == 0) {
state = 1;
wordBegin = strIt;
}
}
}
//reverse the last word
if (strIt > wordBegin) reverse(wordBegin, strIt);
}
int main() {
string strInput;
getline(cin, strInput);
reverseWords(strInput);
cout << strInput;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment