Write a C++ program in which, read a c-string from user. Now your task is to replace all possible pairs of character from input string. Example 1 Example 2 Example 3 Input: Array: good Output: Array: gd Input: Array: abccbd Output: Array: ad Input: Array: civic Output: Array: civic.
#include <bits/stdc++.h>
using namespace std;
//Recursive function to remove two consecutive duplicate characters in a string
void removeDuplicateLetters(char* str)
{
//If the string is empty just return
if (str[0] == '\0')
return;
// if the adjacent characters are same
if (str[0] == str[1]) {
// Shift character by two to the left
int i = 0;
while (str[i] != '\0') {
str[i] = str[i + 2];
i++;
}
removeDuplicateLetters(str);
}
removeDuplicateLetters(str + 1);
}
//Function to check for duplicates. If found call recursive function to remove them
void checkDuplicates(char* str)
{
for(int i = 0; i <= strlen(str); i++)
{
//Check if there exists any consecutive duplicates
if(str[i] == str[i+1])
{
//Call function to remove duplicates
removeDuplicateLetters(str);
}
}
}
// Main Program
int main()
{
char stringToCheck[100];
//Prompt user to enter string
cout<<"Please enter a string: ";
cin>>stringToCheck;
checkDuplicates(stringToCheck);
cout<<"Your string after removing duplicates is: " << stringToCheck << endl;
return 0;
}
Comments
Leave a comment