Reputation: 11
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.
Upvotes: 1
Views: 268
Reputation: 105992
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;
}
}
Upvotes: 3
Reputation: 703
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;
}
Upvotes: 0
Reputation: 1
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;
}
Upvotes: 0
Reputation: 2890
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;
}
Upvotes: 1