jack
jack

Reputation: 31

Remove last occurrence of duplicate character in string

how can i delete the rest of the characters?

s.erase(std::unique(s.begin(), s.end()), s.end());

This only deletes the duplicated characters and doesn't remove the first presence of the character.
Example: "Hello World" would return "he wrd"

Upvotes: 2

Views: 215

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51886

There's no builtin for this function, but you can write your own generic algorithm to accomplish this:

#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>

template <class C>
auto erase_if_duplicate(C& c)
{
    using T = typename C::value_type;

    const auto begin = c.begin();
    const auto end   = c.end();
    std::unordered_map<T, std::size_t> count{};

    std::for_each(
        begin, end,
        [&] (const T& v) { ++count[v]; });

    const auto it = std::remove_if(
        begin, end,
        [&] (const T& v) { return count.at(v) > 1; });

    return c.erase(it, end);
}

int main()
{
    // example usage
    std::string s{"hello world"};
    erase_if_duplicate(s);
    std::cout << s; // he wrd
}

Try it on godbolt.org

Upvotes: 1

silverfox
silverfox

Reputation: 1662

From what I understand, you want to remove all occurrences of a character from a string if it has duplicates (its count is bigger than 2), and the removal is not case-sensitive (meaning H will be treated as h).

So, you can create a frequency map of all character, and if its count is >1 then remove all of its occurrences with erase():

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

int main()
{
    string x; getline(cin, x);
    map<char, int> freq;
    for (size_t i = 0; i < x.size(); i++)
    {
        x[i] = tolower(x[i]); //lowercase all the character
        freq[x[i]]++; //frequency of character
    }

    x.erase(remove_if(x.begin(), x.end(), 
            [&] (const char& c) { return freq[c] > 1; }), 
            x.end());
    cout << x;
}

Output :

Hello world
he wrd

Another example:

ABbcDdDEfF
ace

Upvotes: 0

Related Questions