Created
July 29, 2018 13:53
-
-
Save lnikon/f4f00fb75a0271ea2db4fcd2534b3598 to your computer and use it in GitHub Desktop.
Reverse words in a given string
This file contains hidden or 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> | |
void solution(std::string str) { | |
str += " "; | |
auto size = str.size(); | |
size_t start = 0; | |
for(size_t i = 0; i < size; i++) { | |
size_t end = str.find(' ', start); | |
if(end == std::string::npos) { | |
end = str.size() - 1; | |
} | |
std::string subs = str.substr(start, end - start + 1); | |
std::reverse(std::begin(subs), std::end(subs)); | |
str.replace(start, end - start + 1, subs); | |
start = end + 1; | |
} | |
std::cout << "\nstr:" << str << std::endl; | |
} | |
int main() { | |
solution(std::string("hello friend. it's a sloppy way")); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment