How can I count the number of occurrences of the character '/' in string C?

How to count the number of occurrences in line C /?

I can do it:

int countSlash(char str[])
{
    int count = 0, k = 0;
    while (str[k] != '\0')
    {
          if (str[k] == '/')
              count++;
          k++;
    }
    return count;
}

But this is not an elegant way; any suggestions on how to improve it?

+5
source share
4 answers

strchr would do a smaller loop:

ptr = str;

while ((ptr = strchr(ptr '/')) != NULL)
    count++, ptr++;

I must add that I do not approve of brevity for the sake of brevity, and I always choose the clearest expression, ceteris paribus. I believe that the cycle is strchrmore elegant, but the original implementation in the question is clear and lives inside the function, so I do not prefer one over the other if they both pass unit tests.

+5
source

Yours is enough. Maybe it would look prettier:

int countSlash(char * str)
{
    int count = 0;
    for (; *str != 0; ++str)
    {
        if (*str == '/')
            count++;
    }
    return count;
}
+2
source

, , :

size_t str_count_char(const char *s, int c)
{
    size_t count = 0;

    while (s && *s)
         if (*s++ == c)
             ++count;

    return count;
}

, , , , ; -)

+2

:

int count=0;
char *s=str;
while (*s) count += (*s++ == '/');
0
source

All Articles