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?
Logic to count occurrences of a character in given stringInput a string from user, store it in some variable say str. Input character to search occurrences, store it in some variable say toSearch. Initialize count variable with 0 to store total occurrences of a character. Run a loop from start till end of string str.
lang. StringUtils class provides us with the countMatches() method, which can be used for counting chars or even sub-strings in given String.
One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With