-5

How to count how many different letters are in one text string ?

vinay_Kumar
  • 117
  • 2
  • 10
  • 1
    Google ***determine number of distinct characters in a C string***. Look through the first 10 links for ideas. Implement something based on your findings. (You have to at least try something before the answer will even make sense to you) – ryyker Aug 23 '14 at 17:19

2 Answers2

2

It's quite trivial, actually: you only have to keep track of which characters have already been encountered in the string.

const char *str = "foo bar baz quirk qux";

bool found[1 << CHAR_BIT] = { 0 };

int n_distinct = 0;

for (const char *p = str; *p; p++) {
    unsigned char ch = *p;

    if (!found[ch]) {
        n_distinct++;
        found[ch] = 1;
    }
}

printf("Distinct characters: %d\n", n_distinct);
1

Create a char array called uniqueLetters and a char called currentLetter.Create a for loop that sets currentLetter to each character in the string one by one. Nest another for loop inside of the first loop I described that checks if currentLetter is in the uniqueLetters array. If it is not in the uniqueLetters array add it to the uniqueLetters array. At the end count the length of the uniqueLetters array.

One thing to keep in mind is that 's' and 'S' are considered different characters. If you want to count them as the same letters you will need to add additional logic to check if either the lowercase or uppercase version of the letter exists in the uniqueLetter array.

Hope this helps!

bobbyg603
  • 3,536
  • 2
  • 19
  • 30