Home > Enterprise >  How do i remove every odd time appeared character in string?
How do i remove every odd time appeared character in string?

Time:12-21

I have a string that contains only A, B, C, D. I need to remove all odd-appeared characters in this string. For example if string is "ABBBCA" it will turn into "BA" (first "A" removed because it was first time "A" appeared, then first and third "B" removed, and "C" also, because it was first time it appeared). I'm beginner in coding, so i'm sorry if this question is too simple or something.

I have tried something like this:

#include <iostream>
#include <string>

using namespace std;
int main()
{
    string firstchars = "ABBBCA";
    for (int o = 0; o < firstchars.length(); o   ) {
        firstchars.erase(o,1);
    }

But it just erases every odd element in string, not every odd "A", "B", "C" and "D". And i have "BBA" as output.

CodePudding user response:

Make functions for each part of your code. In this case a function that determines if a value is odd. Then a function that can keep track of the counts per character, a std::map is an ideal datastructure for that. Then use std::remove_if (and erase idiom).

And then C code would look something like this:

#include <algorithm>
#include <iostream>
#include <map>
#include <string>

bool is_odd(unsigned int value)
{
    return ((value % 2) != 0);
}

// returns true if there is an odd number of counts for a character c
bool odd_count(char c)
{
    // keep the same map for each call to this function (avoid global variables!)
    static std::map<char, unsigned int> char_count;
    char_count[c]  ;    // operator [] will add a new entry to the map with value 0 if it does not exist yet.
    return is_odd(char_count[c]);
}

// make copy of string on purpose (normally a string usually is passed by const &
std::string remove_odd_character_occurences_from(std::string string)
{
    auto remove_from = std::remove_if(string.begin(), string.end(), odd_count);
    // https://stackoverflow.com/questions/39019806/using-erase-remove-if-idiom
    string.erase(remove_from, string.end());

    return string;
}


int main()
{
    std::string string{"ABBBCA"};
    std::cout << remove_odd_character_occurences_from(string);

    return 0;
};
  • Related