Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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?

like image 467
JAN Avatar asked Jun 17 '12 19:06

JAN


People also ask

How do you count the occurrences of a given character in a string in C?

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.

How do you count occurrences of particular characters in a string?

lang. StringUtils class provides us with the countMatches() method, which can be used for counting chars or even sub-strings in given String.

How do you count a string occurrence in a 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.


1 Answers

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.

like image 150
pb2q Avatar answered Sep 28 '22 02:09

pb2q