Reverse the letters of every word in a sentence while keeping the words in their original order and the spaces where they are.
Solution
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s = "Learn C++ every day";
auto begin = s.begin();
while (begin != s.end()) {
begin = std::find_if(begin, s.end(), [](char c) { return c != ' '; }); // start of a word
auto end = std::find(begin, s.end(), ' '); // end of the word
std::reverse(begin, end);
begin = end;
}
std::cout << '[' << s << "]\n";
return 0;
}
Output Verified by compiling and running
[nraeL ++C yreve yad]
Find the next non-space (word start) and the next space (word end), reverse that range in place, and continue. Multiple spaces are preserved exactly.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!