How to remove all duplicate characters from a string in C++

4 Answers

0 votes
#include <iostream>
#include <set>

void remove_duplicate_characters(char s[], int len) { 
    std::set<char>st (s, s + len - 1); 
   
    int i = 0; 
    for (auto ch : st) 
        s[i++] = ch; 
    s[i] = '\0'; 
} 
   
int main() 
{ 
   char s[] = "c++ prograaaammmming";
   int len = sizeof(s)/sizeof(s[0]);
    
   remove_duplicate_characters(s, len); 
    
   std::cout << s; 
} 
 
 
 
/*
run:
 
 +acgimnopr
  
*/

 



answered Oct 27, 2019 by avibootz
edited Mar 5 by avibootz
0 votes
#include <algorithm>
#include <iostream>
#include <string>

std::string removeDuplicatesSorted(std::string s) {
    std::sort(s.begin(), s.end());          // sort characters
    auto it = std::unique(s.begin(), s.end()); // remove consecutive duplicates
    s.erase(it, s.end());                   // erase the leftover tail
    
    return s;
}

int main() {
    std::string s = "c++ prograaaammmming";

    std::string result = removeDuplicatesSorted(s);

    std::cout << result << std::endl;     
}

 
 
/*
run:
 
 +acgimnopr
  
*/

 



answered Oct 27, 2019 by avibootz
edited Mar 5 by avibootz
0 votes
#include <iostream>
#include <string>
#include <vector>

std::string removeDuplicatesKeepOrder(const std::string& s) {
    std::vector<bool> seen(256, false);   // ASCII lookup
    std::string result;
    result.reserve(s.size());

    for (unsigned char c : s) {
        if (!seen[c]) {
            seen[c] = true;
            result.push_back(c);
        }
    }

    return result;
}

int main() {
    std::string s = "c++ prograaaammmming laaaaanguage";
    std::cout << removeDuplicatesKeepOrder(s) << std::endl;  
}

 
 
/*
run:
 
c+ progaminlue

*/

 



answered Mar 5 by avibootz
0 votes
#include <iostream>
#include <string>
#include <unordered_set>

std::string removeDuplicatesSet(const std::string& s) {
    std::unordered_set<char> seen;
    std::string result;

    for (char c : s) {
        if (seen.insert(c).second) {  // true if inserted
            result.push_back(c);
        }
    }

    return result;
}

int main() {
    std::string s = "c++ prograaaammmming laaaaanguage";
    std::cout << removeDuplicatesSet(s) << std::endl;  
}

 
 
/*
run:
 
c+ progaminlue

*/

 



answered Mar 5 by avibootz
...