Ad

Finding The Count Of '1' In String Array In C

- 1 answer

I was doing some homework and I need to make a program in C which counts how many times '1' is in the string array. For example I got string array and in it I got 3 strings: D12, B11 and F1.

The program needs to count all of the '1'. For this example that would be 4. How do I accomplish that?

Here is the code that I have so far:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main()
{
    int i=0,N,br=0;
    char s[10][20];

    scanf("%d", &N);
    for(i=0;i<N;i++)
    {
       scanf("%s", &s[i]);
       if(strchr(s[i], '1') != NULL);
       {
           ++br;
       }
    }
    printf("%d", br);
}
Ad

Answer

You should substitute this if statement

   if(strchr(s[i], '1') != NULL);
   {
       ++br;
   }

for the following loop

   for ( const char *p = s[i]; ( p = strchr( p, '1' ) ) != NULL; ++p )
   {
       ++br;
   }

Pay attention to that this call

scanf("%s", &s[i]);

must be changed at least like

scanf("%s", s[i]);
Ad
source: stackoverflow.com
Ad