...

/

Removing Duplicates in a String

Removing Duplicates in a String

This lesson will teach you how to remove duplicates in a string.

What does removing duplicates mean?

Given a string that has repeating adjacent characters, we only want to keep one of each character. To do this, we aim to eliminate the repeating characters. The illustration below shows this process.

Implementing the Code

The code below shows how to do this with recursion. First, let’s see the code, then we can go on to its explanation.

Try the code by changing the values of text to see how it works with other strings.

Press + to interact
#include <iostream>
#include <string>
using namespace std;
void remDuplicates(string &text, int index)
{
if (text[index] == '\0') {return;}
if (text[index] == text[index+1]) {
for(int position = index;position < text.length();position++)
{
text[position] = text[position + 1];
}
remDuplicates(text,index);
}
remDuplicates(text,index+1);
}
int main()
{
string greeting = "Hello Woorldd";
remDuplicates(greeting,0);
cout << greeting << endl;
}

Understanding the Code

The recursive code can be broken down into two parts. The first is the recursive function and the second is the main where the function is called. ...