Question

I wanted to sort a char array in alphabetical order. I used this function:

int cchars(const char* a, const char *b)
{ char temp=*a-*b;
    if (temp>0)
        return 1;
    else if(temp<0)
        return -1;
    else 
        return 0;

} 

and i used this:

qsort(larray,counter,sizeof(char),cchars);

it worked.

But i need to ommit the same characters from this array. For example, if my array is: {'a','z','f','m','d','a'}

it must return as :

{'a','d','f','m','z'}

How can i implement this? Please help.

Was it helpful?

Solution

It will be easiest to remove the duplicates after sorting, since they will be next to each other. Just walk through the array with two iterators, one that always moves forward and one that only moves forward if the next element is not a duplicate:

int i, j;
char prev = -1;
for (i = j = 0; i < (sizeof cchars); i++)
  if (prev != cchars[i])
    prev = cchars[j++] = cchars[i];

You may also want to fill the rest of your array with NUL characters afterwards:

 memset(cchars + j, 0, (sizeof cchars) - j);

That code, applied after the qsort, will convert:

{'a','z','f','m','d','a'} to {'a', 'd', 'f', 'm', 'z', '\0'}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top