LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 3

Reverse each word of a sentence in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links