Counting the number of times a character occurs in a string in C

I am new to C and I am working on my own function explode. I am trying to count how many times the specified character appears in a string.

int count_chars(char * string, char * chr)
{
    int count = 0;
    int i;

    for (i = 0; i < sizeof(string); i++)
    {
        if (string[i] == chr)
        {
            count++;
        }
    }

    return count;
}

It just returns 0 every time. Can someone explain why please? :)

+5
source share
4 answers

Your code is hopelessly corrupted. Here's how it should look:

int count_chars(const char* string, char ch)
{
    int count = 0;
    int i;

    // We are computing the length once at this point
    // because it is a relatively lengthy operation,
    // and we don't want to have to compute it anew
    // every time the i < length condition is checked.
    int length = strlen(string);

    for (i = 0; i < length; i++)
    {
        if (string[i] == ch)
        {
            count++;
        }
    }

    return count;
}

See this code run for example input .

Here is what you are doing wrong:

  • Since you want to find a character, the second parameter should be a character (not a char*). This has consequences later (see No. 3).
  • sizeof(string) . ( ) , (, 4 32- ).
  • , chr. false, if .
  • (string[i]) ( char).

""

, C, , , ( ) .

, " count_chars, , , C, .

int count_chars(const char* string, char ch)
{
    int count = 0;
    for(; *string; count += (*string++ == ch)) ;
    return count;
}

. , , - , .

.

+11

, , string sizeof.

sizeof . . strlen .

+2

C! , !

int count_chars(const char* string, char ch)
{
  int c = 0;
  while (*string) c += *(string++) == ch;
  return c;
}

, :

int c = 0;

.

while (*string)

, . *string. C "null terminated", , 0 ('\ 0'). *string , . C "", "", . *string - , *string true, '\ 0' - false. , , *string .

*(string++)

, , . ++ -, , . , *string , , .

*(string++) == ch

, *string ( ) ch. C ( C bool), "1", "0", .

c += *(string++) == ch;

, += "1", - , , "0", . += :

c = c + (*(string++) == ch);

, .

+=, c , *(variable [index].structure_member [index2]), .

; { while, while.

+2

,

1) , strlen (string).

2) , , , , - char pointer.but, chr, .

if ( string(i)== *chr ) \\ not just ch remember you declared it as a pointer
                      ch gives the address but you want the character so use *ch

strchr.

   int count_chars (char *string, char ch)
       {
         int i;
        if(string=strchr(string,'s'))++i;
            while (string!=NULL)
               if(string=strchr(string+1,chr)
               ++i;
              return i;
        }
0

All Articles