Search code examples
cstringloopsfrequencydigits

Count frequency of digits in string


I need to implement a function that can count the number of digits in a string. So for numbers but also for somehting like: aD23b. If I could make it work...it should look like:
Input: 0912302
Output:
0: 2
1: 1
2: 2
3: 1
4: 0
5: 0
6: 0
7: 0
8: 0
9: 1

At this point I can't code anything that works unfortunately...My basic idea is: Use a loop to check every character from Input, if it's a digit, store it in a second array (let's say frequency). The problems I have are that I need to somehow convert every character into a integer or somehow be able to count how often each digits appears... I was hoping this might work but it doesn't at all:

I forgot to mention I'm a beginner in programming so I would really appreciate if you could give me tips and explanations.

void calc_occurrences(int s[], int occurrences[])
{
int i = 0;
    int j;
    int count = 0;
    while (s[i] != '\0') {
        if (isdigit(s[i])) {
            for (j = 0; occurrences[j] != '\0'; j++) {
                occurrences[j] = s[i];
            }
        }
        i++;
        for (j = i + 1; s[j] != '\0'; j++) {
            if (isdigit(s[i]) == isdigit(s[j])) {
                count++;
                occurrences[j] = 0;
            }
        }

        if(occurrences[i] != 0) {
            occurrences[i] = count;
        }
    }
}

Solution

  • Make an array to count the frequency of each relevant character.

    Something like this:

    #include <stdio.h>
    
    void count_freq(char* str, int freq[10])
    {
        int i = 0;
        while(str[i])  // Loop to end of string
        {
            if (str[i] >= '0' && str[i] <= '9') // Check that the character is in range
            {
                ++freq[str[i]-'0'];  // notice the -'0' to get in range 0..9
            }
            ++i;
        }
    }
    
    int main(void) {
        int freq[10] = {0};             // Array to count occurence
        char str[] = "0034364hh324h34"; // Input string
    
        count_freq(str, freq);          // Calculate frequency
    
        for (int i=0; i < 10; ++i)      // Print result
        {
            printf("%d: %d\n", i, freq[i]);
        }
        return 0;
    }
    

    Output:

    0: 2
    1: 0
    2: 1
    3: 4
    4: 4
    5: 0
    6: 1
    7: 0
    8: 0
    9: 0