Wednesday, March 9, 2011

Code: Remove duplicate characters from string

Earlier we have seen code for checking for duplicates. We are now going to extend that code to remove the duplicates from the string.

void RemoveDuplicates(char* pchStringofDuplicates)
{
      if( NULL == pchStringofDuplicates || NULL == (pchStringofDuplicates +1))
            return ;

      char* pchPointToEnd, *pchPointToStart = pchStringofDuplicates++;
      pchPointToEnd = pchStringofDuplicates;

      while(*pchPointToEnd != NULL)
      {
            char* pchComparator = pchPointToStart;
            while(pchComparator != pchPointToEnd)
            {
                  if(*pchComparator == *pchPointToEnd)
                  {
                        break;
                  }
                  pchComparator++;
            }
            if(pchComparator == pchPointToEnd)
            {
                  *pchStringofDuplicates++ = *pchComparator;
            }
            pchPointToEnd++;
      }
      *pchStringofDuplicates = *pchPointToEnd;
}

Considering second character as tail(at first time), we will compare every character from start to tail, with tail. If we don't found match then we will add the tail in the same string. Do this till end of string.

Note: In C++ we are passing the char array to this function. If you try passing char* string you may get Access Violation error.  

No comments:

Post a Comment