Finding Characters

Difficulty: ★ ★ ☆ ☆

When I was working on last month’s Exercise, I scoured the C library for a function that returned the number of specific characters found in a string. The closest I could find was strchr(), which returns the location of a given character in a string. You can set this function in a loop to find subsequent characters, but what I needed was a tally, a total count of all matching characters in the string.

For example, given the string "She sells seashells by the seashore", how many letters s (lowercase only) are found in the string?

Don’t use your eyeballs to count! No, your task for this month’s Exercise is to code a function charcount(). It accepts two arguments, a string to scan and the character to count. The function returns the number of characters found.

You can use this sample code to get you started, which is missing the charcount() function details, of course:

2023_09_01-Lesson.c

#include <stdio.h>

int charcount(char *s,char c)
{
}

int main()
{
    const int size = 64;
    char buffer[size];
    char c,t;

    printf("Enter a string: ");
    fgets(buffer,size,stdin);
    printf("Enter a character to find: ");
    scanf("%c",&c);

    t = charcount(buffer,c);
    printf("There are %d letters '%c' in: %s",
            t,
            c,
            buffer
          );

    return(0);
}

Here is a sample run from my solution:

Enter a string: She sells seashells by the seashore
Enter a character to find: s
There are 7 letters 's' in: She sells seashells by the seashore

Your task is to complete the charcount() function. Please try this Exercise on your own before you check out my solution.

2 thoughts on “Finding Characters

  1. The seashells thing is about Mary Anning.

    https://en.wikipedia.org/wiki/Mary_Anning

    I threw this together in a hurry and I’m not sure it’s completely bugless. It relies on the fact that a comparison operator like == evaluates to 0 or 1 which can be used to increment a counter. I’m not sure that’s an absolute truth, it could be 0 or not 0 (ie. any non-zero value) which would ruin my idea. However, it works for me.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int charcount(char* str, char c)
    {
        int count = 0;

        for(int i = 0, l = strlen(str); i < l; count+=str[i]==c, i++);
       
        return count;
    }

    int main()
    {
        char vn[] = “snake_case_variable_name”;

        int c = charcount(vn, ‘_’);

        printf(“%d\n”, c);

        return EXIT_SUCCESS;
    }

Leave a Reply