is there a c function that counts the number occurences of a character in a string. For example, given
somthing like...
(apple, p)
will return 2 (for two p's)?
Thanks,
Bill
is there a c function that counts the number occurences of a character in a string. For example, given
somthing like...
(apple, p)
will return 2 (for two p's)?
Thanks,
Bill
no but I'll make one for you hang on...
writing your own should not be a problem.
You would call this likeCode:int check(char *str_ptr, char ch) { int count = 0; while(*str_ptr) { if(*str_ptr == ch) count++; str_ptr++; } return count; }
Code:total = check("apple", 'p');
Code:#include <stdio.h> #include <string.h> #include <stdlib.h> int countThem(char inputString[BUFSIZ], char inputLetter) { int j = -1; int k = 0; do { j++; if(inputString[j] == inputLetter) { k++; } } while(inputString[j]); return k; } int main(void) { char a[20] = "apple"; int i = countThem(a,'p'); printf("%d",i); return 0; }
Last edited by Brian; 01-29-2002 at 02:05 PM.
mine's better :P
Brian - yours doesn't work if the requested letter's the first in the string...
Also, they're both case sensitive.
-Govtcheez
[email protected]
oops lol . *quick edit*
That wasn't specified in the question, maybe he wants it case sensitive.Also, they're both case sensitive.