Home > Back-end >  Recursion to remove duplicate characters c
Recursion to remove duplicate characters c

Time:12-28

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

using namespace std;

void rmvdupli(string s)
{
    if (s.length() == 1)
    {
        cout << s;
        return;
    }
    char c = s.at(0);
    if (((s.substr(1)).find(c)) >= 0)
        cout << "";
    else
        cout << c;
    rmvdupli(s.substr(1));
}

int main()
{
    cout << "Enter the string " << endl;
    string s;
    cin >> s;
    rmvdupli(s);
    return 0;
}

Output

Enter the string

ababcdc

c

What is the problem with the code? It seems perfectly alright but answer is not coming!!

CodePudding user response:

The below line:

if (((s.substr(1)).find(c)) >= 0)

should be changed to:

if (s.substr(1).find(c) != std::string::npos)

It basically means that c is found in s.substr(1).

find returns std::string::npos if the character is not found.

CodePudding user response:

I have tried to solve this problem of yours.

What I have done is, I have replaced duplicate characters with whitespace.

if you want to remove whitespace you can find the code easily on internet.

C Code:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void RemoveDuplicateChar(string inputString)
{
    if(inputString.length() == 1){
        cout << inputString;
        cout << "\nIt has only one character";
    }else{
       int  stringLength = inputString.length();
       cout<< "Original string: ";
       cout << inputString;
       cout << "\n";
            for(int i =0 ; i<stringLength; i  ){
                for(int j = i 1; j< stringLength; j  ){
                    if(inputString[i] == inputString[j]){
                        inputString[j] = ' ';
                        
                    }else{
                        continue;
                    }
                }
            }
            cout << "Duplicate character removed\n";
            cout << "New String: ";
            cout << inputString;
            
            
            
        
    }
}

int main()
{
    string input;
    cout << "Enter a string with repeated characters: ";
    cin >> input;
    RemoveDuplicateChar(input);
    

    return 0;
}

Output:

Enter a string with repeated characters: ababcdc

Original string: ababcdc

Duplicate characters removed

New String: ab cd

  • Related