LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 10

Remove duplicate characters from a string in C++ Solution, output & explanation

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

Remove repeated characters from a string, keeping only the first occurrence of each and the original order.

Solution
main.cpp
#include <array>
#include <iostream>
#include <string>

std::string remove_duplicates(const std::string& s) {
    std::array<bool, 256> seen{};
    std::string out;
    for (unsigned char c : s) {
        if (!seen[c]) {
            seen[c] = true;
            out += static_cast<char>(c);
        }
    }
    return out;
}

int main() {
    for (std::string s : {"programming", "mississippi", "LearnFrenzy", "aaaa"})
        std::cout << s << " -> " << remove_duplicates(s) << '\n';
    return 0;
}

Output Verified by compiling and running

programming -> progamin
mississippi -> misp
LearnFrenzy -> LearnFzy
aaaa -> a

A table of 256 flags records which characters have appeared. Unlike sort + unique, this keeps the original order. Upper- and lowercase letters are different characters.

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