Tuesday 28 January 2014

Removing duplicates from the string

Here's the code to remove duplicates from a given string. In this program, I've used a variable called tail which is used to remove all the duplicates and also acts as boundary for string comparison.


  1 #include<iostream> 
  2 using namespace std;
  3 int main() 
  4 { 
  5     char *str; 
  6     str=new char[50]; 
  7     cout<<"enter"; 
  8     cin>>str; 
  9     int tail = 1,len;
 10     len=strlen(str); 
 11      for (int i = 1; i < len; ++i) {
 12         int j; 
 13         for (j = 0; j < tail; ++j) {
 14              if (str[i] == str[j]) break;
 15          } 
 16         if (j == tail) { 
 17             str[tail] = str[i]; 
 18             ++tail; 
 19          } 
 20     } 
 21  str[tail] = 0; 
 22  for(int i=0;i<len;i++) 
 23      cout<<str[i]; 
 24  return 0;
 25 }
I appreciate your suggestions if any....Thank you

No comments:

Post a Comment