
- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
String program to count characters
Implementation
Now, we shall see the actual implementation of the program −
#include <stdio.h> int main() { char s[] = "TajMahal"; // String Given char ch = 'a'; // Character to count int i = 0; int count = 0; // Counter while(s[i] != '\0') { if(s[i] == ch) count++; i++; } if(count > 0) { if(count == 1) printf("%c appears %d time in '%s'", ch, count, s); else printf("%c appears %d times in '%s'", ch, count, s); } else printf("%c did not appear in %s", ch, s); return 0; }
Output
Output of this program should be −
a appears 3 times in 'TajMahal'
string_programs_in_c.htm
Advertisements