Remove duplicate string in C++


This is a C++ program that removes duplicate characters from a given string. The program works as follows:

  • The input string str is passed to a function called removeduplicate, along with the length of the string n.
  • The function removeduplicate initializes an integer variable index to 0, which will be used to keep track of the current index in the output string.
  • The function then iterates over each character in the input string str using a nested for loop. The outer loop starts at the first character of the string and goes up to the last character, while the inner loop starts at the beginning of the string and goes up to the current index of the outer loop.
  • For each character in the outer loop, the inner loop checks whether the character is already present in the output string. If it is, the inner loop breaks and moves on to the next character. If it is not, the current character is added to the output string at the current index index, and index is incremented.
  • Finally, the output string is returned from the function.
  • In the main function, an input string str is defined and its length is calculated using the sizeof operator. The removeduplicate function is then called with the input string and its length, and the resulting output string is printed to the console using the cout object.

Overall, this program demonstrates how to remove duplicate characters from a string in C++ by iterating over the string and keeping track of which characters have already been added to the output string.

Source Code

#include<iostream>
using namespace std;
char *removeduplicate(char str[],int n)
{
   int index=0;
   for (int i=0;i<n;i++)
   {
        int j;
        for(j=0;j<i;j++)
        {
            if(str[i]==str[j])
            {
               break;
            }
        }
        if(j==i)
        {
            str[index++]=str[i];
        }
   }
   return str;
}
int main()
{
   char str[]= "tutorjoes";
   int n=sizeof(str)/sizeof(str[0]);
   cout<<"\n"<<removeduplicate(str,n);
   return 0;
}
To download raw file Click Here

Output

tuorjes

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples