Normalise usernames: trim spaces, lower-case them, drop empty or too-short names (fewer than 3 characters), then sort and remove duplicates; print the result.
Solution
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
std::string normalise(std::string s) {
auto not_space = [](unsigned char c) { return !std::isspace(c); };
s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_space)); // trim left
s.erase(std::find_if(s.rbegin(), s.rend(), not_space).base(), s.end()); // trim right
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
int main() {
std::vector<std::string> users{" Asha ", "ravi", "ASHA", "", "Jo", " meena", "Ravi ", "zoya"};
std::transform(users.begin(), users.end(), users.begin(), normalise);
std::erase_if(users, [](const std::string& u) { return u.size() < 3; });
std::sort(users.begin(), users.end());
users.erase(std::unique(users.begin(), users.end()), users.end());
for (const auto& u : users) std::cout << u << ' ';
std::cout << users.size() << '\n';
return 0;
}
Output Verified by compiling and running
asha meena ravi zoya 4
Trimming uses find_if from both ends (base() turns the reverse iterator back into a forward one). erase_if removes short names; sort + unique + erase removes duplicates.
More STL Algorithms and Iterators 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!