C program to find frequency of each digit in a string


Suppose we have a string s. The s contains letters and digits both. We shall have to find frequencies of each digit and display them. To do this we can make an array of size 10 for each digits (0 through 9), initially all elements are 0 inside the array, then when we encounter a digit simply increase the value of that index and finally print them all.

So, if the input is like s = "we85abc586wow236h69", then the output will be (Number 2, Freq 1) (Number 3, Freq 1) (Number 5, Freq 2) (Number 6, Freq 3) (Number 8, Freq 2) (Number 9, Freq 1)

To solve this, we will follow these steps −

  • Define an array freq of size: 10 and initialize all elements with 0

  • for initialize i := 0, when i < size of s, update (increase i by 1), do:

    • if s[i] is numeric, then:

      • increase freq[s[i] - ASCII of '0'] by 1

  • for initialize i := 0, when i < 10, update (increase i by 1), do:

    • if freq[i] > 0, then:

      • display (Number i , Freq freq[i])

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#include <string.h>
void solve(char *s){
    int freq[10] = {0};
    for(int i = 0; i < strlen(s); i++){
        if(s[i] >= '0' && s[i] <= '9'){
            freq[s[i] - '0']++ ;    
        }
    }
    for(int i = 0; i<10; i++){
        if(freq[i] > 0)
            printf("(Number %d, Freq %d)
", i, freq[i]);     } } int main(){     char *s = "we85abc586wow236h69";     solve(s); }

Input

"we85abc586wow236h69"

Output

(Number 2, Freq 1)
(Number 3, Freq 1)
(Number 5, Freq 2)
(Number 6, Freq 3)
(Number 8, Freq 2)
(Number 9, Freq 1)

Updated on: 08-Oct-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements