Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Remove all consecutive duplicates from a string using STL in C++

  • Last Updated : 26 May, 2019

Given a string S, remove all the consecutive duplicates in this string using STL in C++

Examples:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: Geeks for geeks
Output: Geks for geks

Input: aaaaabbbbbb
Output: ab

Approach:
The consecutive duplicates of the string can be removed using unique() function provided in STL.

Below is the implementation of the above approach.




#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    string str = "Geeksforgeeks is best";
  
    // Using unique() method
    auto res = unique(str.begin(), str.end());
  
    cout << string(str.begin(), res)
         << endl;
}
Output:
Geksforgeks is best
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!