Counting number of occurrences of a char in a string in C

Solution 1:

Here's the way I'd do it (minimal number of variables needed):

for (i=0; s[i]; s[i]=='.' ? i++ : *s++);

Solution 2:

OK, a non-loop implementation (and yes, it is meant as a joke).

size_t CountChars(const char *s, char c)
{
  size_t nCount=0;
  if (s[0])
  {
    nCount += ( s[0]==c);
    if (s[1])
    {
      nCount += ( s[1]==c);
      if (s[2])
      {
        nCount += ( s[2]==c);
        if (s[3])
        {
          nCount += ( s[3]==c);
          if (s[4])
          {
            nCount += ( s[4]==c);
            if (s[5])
            {
              nCount += ( s[5]==c);
              if (s[6])
              {
                nCount += ( s[6]==c);
                if (s[7])
                {
                  nCount += ( s[7]==c);
                  if (s[8])
                  {
                    nCount += ( s[8]==c);
                    if (s[9])
                    {
                      nCount += ( s[9]==c);
                      if (s[10])
                      {
                        /* too long */
                        assert(0);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  return nCount;
}

Solution 3:

Look, ma, no loops.

int c = countChars( s, '.' );

int countChars( char* s, char c )
{
    return *s == '\0'
              ? 0
              : countChars( s + 1, c ) + (*s == c);
}

But, I'd actually use a loop, since that's the correct control structure to use.

Solution 4:

Without loops is going to be hard since there's no standard C library function that does this and you need to look at all chars :)

I'll take the obvious solution:

int i, count;
for (i=0, count=0; str[i]; i++)
  count += (str[i] == '.');

Feel free to squeeze the two lines of actual code into one if you have to :)

Solution 5:

If you're keen on a one-liner (well, two-):

size_t count = 0;
while(*str) if (*str++ == '.') ++count;