LearnFrenzy
Sign in Take a free test

References: lvalue and rvalue · Reference Programs · Question 10

Trim and lowercase a string in place in C++ Solution, output & explanation

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

Write void normalize(std::string& s) that removes leading and trailing spaces and lowercases the text in place, and apply it to several inputs stored in a vector.

Solution
main.cpp
#include <cctype>
#include <iostream>
#include <string>
#include <vector>

void normalize(std::string& s) {
    auto first = s.find_first_not_of(' ');
    if (first == std::string::npos) { s.clear(); return; }
    auto last = s.find_last_not_of(' ');
    s = s.substr(first, last - first + 1);
    for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}

int main() {
    std::vector<std::string> inputs{"  Hello World ", "C++", "   ", " MiXeD Case"};
    for (auto& s : inputs) normalize(s);
    for (const auto& s : inputs) std::cout << '[' << s << ']';
    std::cout << '\n';
    return 0;
}

Output Verified by compiling and running

[hello world][c++][][mixed case]

The function changes the caller's string through the reference, and the auto& loop passes each vector element itself. An all-space string becomes empty.

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