简体   繁体   中英

Finding character in string

Given a string and a character, I have to find how many times the character exists in the string.

This is what I have so far:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main ()
{
  char string[10];
  char c1, c2;
  int contador, i, l, n;

  printf ("Introduza uma string e dois caracteres.\n");
  scanf ("%s %c %c", &string[i], &c1, &c2);

  l = strlen (string);
  contador = 0;

  for (n = 0; n < l; n++)
    {
      if (c1 == string[i])
    {
      contador = contador + 1;
    }
    }
  printf ("%d\n", contador);
}

The text in printf is in portuguese, and it means "Introduce a string and two characters". The second character is there for later.

Would appreciate any help you can give.

You have to made some changes:
Change

 scanf ("%s %c %c", &string[i], &c1, &c2);  

to

 scanf ("%s %c %c", string, &c1, &c2);  

and

 if (c1 == string[i])  

to

 if (c1 == string[n])  

Also you can keep if (c1 == string[i]) unchanged by changing for (n = 0; n < l; n++) to for (i = 0; i < l; i++) .
Here is the modified code snippet

printf ("Introduza uma string e dois caracteres.\n");
scanf ("%s %c %c", string, &c1, &c2);  


l = strlen (string);
contador = 0;

for (n = 0; n < l; n++)
{
      if (c1 == string[n])
      {
          contador = contador + 1;
      }
}

Here is a simple implementation of a function that does what you need.

int strnchr(char *string, char ch) {
    int i, len = strlen(string), found = 0;
    for(i = 0; i < len; i++)
        if(string[i] == ch)
            found++;
    return found;
}

Here is the modified code, and the 'why' is haccks 's answer .

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
  char string[10];
  char c1;
  int contador, l, n;

  printf ("Introduza uma string e dois caracteres.\n");
  scanf ("%s %c", string, &c1);

  l = strlen (string);
  contador = 0;

  for (n = 0; n < l; n++)
    {
      if (c1 == string[n])
          contador++;
    }

  printf ("%d\n", contador);

  return 0;
}

If you need a fast implementation of this function you can use the strchr -function from the standard c library, which should be well optimised on most common systems.

int strnchr(char *str, char ch) {
   int i;

   for (i = 0; (str = strchr(str, ch)) != NULL; i++) {
      if (++str == '\0') {
         break;
      }
   }

   return i;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM