Cutik
Cutik

Reputation: 55

CountChars array string loop function letter occurrence

I'm trying to advance my skills in c, I'm a bit confused when it comes to understand different ways to calculate the occurrence of letters in a string with a function, would be great to receive different views on how I could improve the code or a new way to count how many times a letter occur in a string with a function.

Any advice?

#include <stdio.h>

int countingCharacters(char *message, int size, char charToBeCounted);


int main() {

    char arrMess[13] = { "hejsanSvejsan" };
    char charsToBeCounted = 'a';

    for (int i = 'a'; i <= 'z'; i++) {

        printf("%c, %d:\n", charsToBeCounted, countingCharacters(arrMess, 13, charsToBeCounted));
        charsToBeCounted++;

    }
    getchar();
    return 0;
}

int countingCharacters(char *message, int size, char charToBeCounted) {

    int counter = 0;
    int i = 0;

    while (i < size)
    {
        if (message[i] == charToBeCounted)
            counter++;
        i++;
    }
    return counter;
}

Upvotes: 1

Views: 73

Answers (2)

Chris Turner
Chris Turner

Reputation: 8142

If your code is counting every letter (a to z) in the string, you could do it one pass and use an array to track how many there are of each. Something along the lines of:

void countingCharacters(char *message, unsigned int count[]) {
    while(*message) {
        if(isalpha(*message)) {
            count[tolower(*message)-'a']++;
        }
        message++;
    }
}

int main() {

    char arrMess[] = { "hejsanSvejsan" };
    char i;
    unsigned int count[26] = { 0 };

    countingCharacters(arrMess,count);
    for(i='a';i<='z';i++) {
        printf("%c, %d:\n", i, count[i-'a']);
    }
    return 0;
}

I removed the hard coding of the size of arrMess, by the way, because it was wrong. Your string was 13 characters long which would be too big to fit into a char array of size 13 as you need 1 extra to store the '\0' at the end of it.

Upvotes: 1

Nuntipat Narkthong
Nuntipat Narkthong

Reputation: 1397

You can omitted size and check for '\0' at the end of the string.

int countingCharacters(char *message, char charToBeCounted) {
    int counter = 0;
    while (message != '\0')
    {
        if (*message == charToBeCounted)
            counter++;
        message++;
    }
    return counter;
}

Upvotes: 0

Related Questions