Page 98, Exercise 1 : Count the characters in a string

 

Call: char s1[MAX_SIZE] = {"hello, world!"};
countChars(s1);

void countChars(char *s)

{ /*Exercise 1*/

  int counts[26];

  int i;

  char ch;

  for (i = 0; i < 26; i++) /* set counts to 0 */

      counts[i] =0;

	  

   for (i = 0; i < strlen(s); i++)

      if ( (isupper(s[i])) || (islower(s[i]))) {

	       ch = toupper(s[i]); /* make case insensitive */

		   counts[(int)ch-65]++; /*Subtract ASCII value for A */

	   }

	for (i = 0; i < 26; i++)

	  printf("[%c: %d]  ", (char)(65+i), counts[i]);

	printf("\n");

}