Last active
December 25, 2015 09:19
-
-
Save ravichandrae/6952899 to your computer and use it in GitHub Desktop.
This program reverses the words in the given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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