Finding Characters – Solution

The challenge for this month’s Exercise is to write the charcount() function, which returns the number of characters in a string. The character matches exactly, so don’t worry about checking uppercase and lowercase differences.

My solution involves using a while loop to move a pointer through the string. An if comparison checks for the given character, tallying the result in variable total. Here is the full code, with my charcount() function up top:

2023_09-Exercise.c

#include <stdio.h>

int charcount(char *s,char c)
{
    int total = 0;

    while(*s)
    {
        if( *s==c )
            total++;
        s++;
    }

    return(total);
}

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);
}

Pointer s represents the string passed. The while loop processes the entire string: while(*s) with the s pointer address incremented within the loop: s++ It’s okay to modify this pointer variable within the charcount() function as this change doesn’t affect the pointer in the main() function.

Variable total is initialized to zero: int total = 0; It’s incremented only when a match is found inside the string. When no characters match, the preset value zero is returned.

Here is a sample run of my solution:

Enter a string: Peter Piper picked a peck of pickled peppers
Enter a character to find: p
There are 7 letters 'p' in: Peter Piper picked a peck of pickled peppers

I hope your solution met with success. Remember, mine isn’t the only approach to solving the problem.

3 thoughts on “Finding Characters – Solution

  1. So is a truthy expression guaranteed to always evaluate to 1, or can it be any non-zero value? (The idea that it could be the latter is probably just a figment of my addled brain.)

  2. @ChrisWebb

    »So is a truthy expression guaranteed to always evaluate to 1, or can it be any non-zero value?«

    Yes, the ISO/IEC 9899:1989 “C” standard already mandated this behavior for logical as well as relational operators—see subclauses starting from 6.3.8 for relational operators and 6.3.13 for logical operators.

    »In each case the standard states that these operators “shall yield 1 if the specified relation is true and 0 if it is false”.«

    Moreover, as I just verified, this behavior was mandated even before the language was standardized… as specified in Appendix A of “The C Programming Language”:

    A.7.6:
    »The operators … all yield 0 if the specified relation is false and 1 if it is true.«

    (Of course, this only holds for logical operators, not for bitwise ones.)

Leave a Reply