Skip to content

Instantly share code, notes, and snippets.

@lnikon
Created July 29, 2018 13:53
Show Gist options
  • Save lnikon/f4f00fb75a0271ea2db4fcd2534b3598 to your computer and use it in GitHub Desktop.
Save lnikon/f4f00fb75a0271ea2db4fcd2534b3598 to your computer and use it in GitHub Desktop.
Reverse words in a given string
#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