LearnFrenzy
Sign in Take a free test

STL Algorithms and Iterators · STL Algorithm Programs · Question 9

Clean up usernames with erase_if and unique in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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.

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