簡體   English   中英

我如何刪除字符串中每一個奇數時間出現的字符?

[英]How do i remove every odd time appeared character in string?

我有一個僅包含 A、B、C、D 的字符串。我需要刪除該字符串中所有出現的奇數字符。 例如,如果字符串是“ABBBCA”,它將變成“BA”(第一個“A”被刪除,因為它是第一次出現“A”,然后第一個和第三個“B”被刪除,還有“C”,因為它是第一次出現它出現的時間)。 我是編碼初學者,如果這個問題太簡單或什么的,我很抱歉。

我試過這樣的事情:

#include <iostream>
#include <string>

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

但它只是擦除字符串中的每個奇數元素,而不是每個奇數“A”、“B”、“C”和“D”。 我有“BBA”作為輸出。

沿着這些思路,也許:

std::string s = "ABBBCA";
std::bitset<4> seen;
s.erase(
    std::remove_if(s.begin(), s.end(), [&](char c) {
        return seen[c - 'A'].flip();
    }),
    s.end()
);

演示

為代碼的每個部分創建函數。 在這種情況下,一個函數確定一個值是否為奇數。 然后是一個可以跟蹤每個字符計數的函數,std::map 是一個理想的數據結構。 然后使用 std::remove_if (並擦除成語)。

然后 C++ 代碼看起來像這樣:

#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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM