IHYPRESS.NET
C
HOME | ASP | C | CSS | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
Earn Free Bitcoin
CStrings ❯ Counting Characters
<08.07>
#include <stdio.h> #include <string.h> // counts the number of times ch occurs in string str. int count (char ch, const char *str) { int ans; if (str[0] == '\0') /* simple case */ ans = 0; else /* redefine problem using recursion */ if (ch == str[0]) /* first character must be counted */ ans = 1 + count(ch, &str[1]); else /* first character is not counted */ ans = count (ch, &str[1]); return (ans); } int main(void) { char str[80]; /* string to be processed */ char target; /* character counted */ int my_count; printf ("Enter a sentence up to 79 characters > "); fgets (str, 79, stdin); /* read in the string */ printf ("Enter the character you want to count: "); scanf ("%c", &target); my_count = count(target, str); printf ("The number of '%c' in '%s' is %d.\n", target, str, my_count); // fix to make the output look better str[strlen(str)-1] = '\0'; printf ("The number of '%c' in '%s' is %d.\n", target, str, my_count); return (0); }
Hergestellt in Deutschland / Made in Germany
Enter a sentence up to 79 characters > You can observe a lot by just watching Enter the character you want to count: o The number of 'o' in 'You can observe a lot by just watching ' is 3. The number of 'o' in 'You can observe a lot by just watching' is 3.
COPYRIGHT © 2015-2024 IHYPRESS.NET. A DIVISION OF IHY PRESS. ALL RIGHTS RESERVED.