Morteza R
Morteza R

Reputation: 2319

Constructing an array of unique characters from a char array

Suppose I have a char array and I want to construct a new one that only contains unique characters (i.e. the array contains only one occurrence of each character). This is part of a response to an exercise in an introductory C book where advanced concepts like pointers are not yet introduced. So, the answer should not make use of pointers.

int i, j, n;
char list[MAX_SIZE], unique_list[MAX_SIZE];
char curr;
n = 0;
for(i = 0; i < strlen(list) ; ++i){
    curr = list[i];
    for (j = 0; j <= n; ++j){
        if (unique_list[j] == curr)
            break;
        else
            unique_list[n++] = curr;
    }
}

When I run this however, it doesn't seem to work. Apparently it is stuck in a permanent loop and unique_list[j] is always equal to curr (the current character being read from the char array). However I am not initializing unique_list so why does it always contain the same characters as the ones being read from the main array?

Upvotes: 1

Views: 1292

Answers (2)

Shafi
Shafi

Reputation: 1970

You need to rethink the logic. For each character in the list, you need to check if that character is in the unique_list. If not, then add the character to the unique_list. In other words, adding the character needs to be after the j loop, not inside the j loop. Something like this:

int i, j, n;
char list[MAX_SIZE], unique_list[MAX_SIZE];
char curr;
n = 0;
for(i = 0; i < strlen(list) ; ++i){
    curr = list[i];
    for (j = 0; j < n; ++j){
        if (unique_list[j] == curr)
            break;
    }
    if(j == n) 
        unique_list[n++] = curr;
}

Upvotes: 2

Ashraful Islam
Ashraful Islam

Reputation: 12840

To do that in complexity O(n) use a flag array.
Here is the complete code

int i, j, n;
char list[MAX_SIZE], unique_list[MAX_SIZE];
int flag[128];
memset(flag,1, sizeof(flag));
char curr;
n = 0;
for(i = 0; i < strlen(list) ; ++i)
{
    curr = list[i];
    if(flag[curr]) {
        unique_list[n++] = curr;
        flag[curr] = 0;
    }
}

if you don't know what memset is you can check this memset function in c language

Upvotes: 1

Related Questions