How can I count the number of occurrences in a C string of /
?
I can do this:
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?
strchr
would make a smaller loop:
ptr = str;
while ((ptr = strchr(ptr '/')) != NULL)
count++, ptr++;
I should add that I don't endorse brevity for brevity's sake, and I'll always opt for the clearest expression, all other things being equal. I do find the strchr
loop more elegant , but the original implementation in the question is clear and lives inside a function, so I don't prefer one over the other, so long as they both pass unit tests.
Yours is good enough. Maybe, this would look prettier to some:
int countSlash(char * str)
{
int count = 0;
for (; *str != 0; ++str)
{
if (*str == '/')
count++;
}
return count;
}
Generic interface, obvious approach, appropriate types and purely idiomatic expressions:
size_t str_count_char(const char *s, int c)
{
size_t count = 0;
while (s && *s)
if (*s++ == c)
++count;
return count;
}
Oli Charlesworth would probably raise concerns regarding assignments and conditionals on the same line, but I think it's fairly well hidden ;-)
This will also work:
int count=0;
char *s=str;
while (*s) count += (*s++ == '/');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.