Print number of distinct characters in a string.

How do I implement a C program that reads a string and prints a table with the number of occurrences of each character in the string.
Ex: Rubber. r = 2, u = 1, b = 2, e = 1.

Showing Answers 1 - 4 of 4 Answers

Simple, fairly brain-dead example. Assumes any input characters fall into the range [0...CHAR_MAX).

Code
  1. #include <stdio.h>

  2. #include <ctype.h>

  3. #include <limits.h>

  4.  

  5. int main(int argc, char **argv)

  6. {

  7.   int counts[CHAR_MAX] = {0};

  8.   char *p;

  9.   int i;

  10.  

  11.   if (argc < 2)

  12.   {

  13.     fprintf(stderr, "USAGE: %s <string>

  14. ", argv[0]);

  15.     return 0;

  16.   }

  17.  

  18.   for(p = argv[1]; *p != 0; p++)

  19.     counts[(size_t) *p]++;

  20.  

  21.   for (i = 0; i < CHAR_MAX; i++)

  22.   {

  23.     if (counts[i] > 0)

  24.     {

  25.       if (isprint(i))

  26.       {

  27.         printf("%c: %02d

  28. ", i, counts[i]);

  29.       }

  30.       else

  31.       {

  32.         printf("%x: %02d

  33. ", i, counts[i]);

  34.       }

  35.     }

  36.   }

  37. }

  38.  

  Was this answer useful?  Yes

Code
  1.  

  2. int main()

  3.  

  4. {

  5.  

  6. char str[11]="aabcadefge";

  7. int a[26];

  8. for(int i=0;i<26;i++) a[i]=0;

  9. int couner=0;

  10. for(int i=0;str[i]!=;i++){

  11.         a[(str[i]-a)]+=1;

  12. }

  13.  

  14.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions