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?
strchrwould make a smaller loop: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
strchrloop 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.