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.
More References: lvalue and rvalue practice questions
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!