Search code examples
cfor-loopif-statementc-stringsdigits

problem in comparing string to a integer i guess


This code is not working, how many times the number 0 to 9 is repeated in a given string.

This is the question, itis from hackerrank:

Given a string, S, consisting of alphabets and digits, find the frequency of each digit in the given string.

I can't find any error in my logic.

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

int main()
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    char s[1000];
    int count[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    char temp;
    scanf("%s", s);

    for (int i = 0; i < 10; i++)
    {
        temp = i;

        for (int j = 0; j < strlen(s); j++)
        {
            if (s[j] == i)
            {
                count[i] = count[i] + 1;
                continue;
            }
            else
            {
                continue;
            }
        }
    }

    for (int k = 0; k < 10; k++)
    {
        printf("%d ", count[k]);
    }

    return 0;
}

Solution

  • At least you need to write

    if (s[j] == i + '0')
    

    Otherwise you are trying to compare a character like '0' that can have the ASCII code 48 with integer 0.

    But in any case the for loops are inefficient.

    It is better to write:

    for (const char *p = s; *p; ++p)
    {
        if ('0' <= *p && *p <= '9') ++count[*p - '0'];
    }