-
strchr
I know that strchr, searches for the first occurences of a char in a string... I just wanted know if I can use this code to count characters in a string as example.
String: An apple a day keeps the doctor away
Char to search: a
Result: Found a 6 times in String.
1. I have figured out something like this.
Code:
#include <string.h>
#include <stdio.h>
int main(void)
{
char string[15];
char *ptr, c = 'i';
int i;
strcpy(string, "This is a string");
ptr = strchr(string, c);
if (ptr)
while(ptr)
{
ptr = strchr(string, NULL);
i++;
}
printf("Char %c, found %d times in string", c, i);
else
printf("Char was not found in string");
}
But this code didn't work... so I just need a bugfix in this code could you help me out a little bit ???
2. How do I get this code to find also the Uppercase and the Lowercase 'A' in this code ?
Thanks in advance
Client
-
Do you have to use strchr? its easy enough to do without it
Code:
#include <stdio.h>
#include <ctype.h>
int main( void )
{
char string[] = "An apple a day keeps the doctor away";
char *p = string;
char ch;
int count = 0;
printf( "\nEnter character to search for: ");
ch = getchar();
ch = tolower( ch ); //ensure ch is lowercase
// all processing done here
while( *p )
{
if( tolower( *p ) == ch ) //test ch against a lowercase *p
++count; // if the same increment count
++p;
}
//display results
printf( "\n%c occured %d times in the string \"%s\"\n", ch, count, string );
return 0;
}
-
Or the strchr() method:
Code:
#include <string.h>
#include <stdio.h>
int main(void)
{
char string[30];
char *ptr, c = 'i';
int i = 0;
strcpy(string, "This is a string");
ptr = strchr(string, c);
while ((ptr = strchr(ptr, c)) != NULL)
{i++;ptr++;}
printf("Char %c, found %d times in string", c, i);
return (0);
}
Three main things wrong with the original code.
- string was 15 bytes long, but the text strcpy()'d into was 16 bytes. Instant buffer overflow... oops.
- i was not initialised before use. You must set it to 0 first!
- incorrect args passed to strchr().
Have fun.........