problem_solving

How to remove duplicate char from a string in C++

To remove duplicate characters from a string in C++, you can use the `std::string::erase` and `std::string::find` functions in a loop. Here’s an example code snippet that demonstrates how to remove duplicate characters from a string:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World";
    int i = 0;
    while (i < str.length()) {
        char c = str[i];
        size_t pos = str.find(c, i + 1);
        if (pos != std::string::npos) {
            str.erase(pos, 1);
        } else {
            i++;
        }
    }
    std::cout << str << std::endl;  // Output: Helo Wrd
    return 0;
}

In this example, the code loops through each character in the string and checks if there is another occurrence of that character later in the string using the `std::string::find` function. If a duplicate character is found, it is removed using the `std::string::erase` function. The loop continues until all duplicate characters have been removed. Finally, the resulting string is printed to the console.

Note that this implementation only removes consecutive duplicate characters. If you need to remove all duplicate characters (not just consecutive ones), you’ll need to use a different approach, such as a hash set to keep track of which characters have already been seen.

To remove side duplicates (i.e., duplicates that are next to each other) in a string in C++, you can use the `std::unique` function from the `<algorithm>` library along with the `std::string::erase` function. Here’s an example code snippet that demonstrates how to remove side duplicates in a string:

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

int main() {
    std::string str = "aaabbbccc";
    auto new_end = std::unique(str.begin(), str.end());
    str.erase(new_end, str.end());
    std::cout << str << std::endl;  // Output: abc
    return 0;
}

In this example, the `std::unique` the function is used to remove side duplicates in the string. The function takes two parameters: the beginning and end iterators of the string. It returns an iterator to the new end of the range that contains the unique elements. The `std::string::erase` function is then used to remove the elements from the end of the range up to the new end iterator. The resulting string is then printed to the console.

Note that the `std::unique` function only removes consecutive duplicates, so if there are non-consecutive duplicates in the string, they will not be removed. If you want to remove all duplicates (not just side duplicates), you can use the `std::set` container to store the unique elements and then construct a new string from the set.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top