OiO.lk Blog C# How can I find the number of unique characters in a string?
C#

How can I find the number of unique characters in a string?


I have found nothing particular for this purpose.

I am trying to figure out a function that counts each of the characters’ occurrences in a string, so that I can pull them out at the end from the length to find how many homogeneous characters are used in that string.

I’ve tried with nested loop, the first to apply and the second to scan the string and conditionally fulfill the character if it does not appear elsewhere in the string:

size_t CountUniqueCharacters(char *str)
{
    int i,j;
    char unique[CHAR_MAX];
    for(i=strlen(str); i>=0; i--)
    {
        for(j=strlen(str); j>=0; j--)
        {
            if(str[i] != unique[j])
                unique[j] = str[i];
        }
    }
    return strlen(unique);
}

This didn’t work well.

This is useful if you are willing to limit someone to type lazy names such as "aaaaaaaaaaaaa".



You need to sign in to view this answers

Exit mobile version