forked from portfoliocourses/c-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count_letters.c
40 lines (34 loc) · 1022 Bytes
/
count_letters.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*******************************************************************************
*
* Program: Count letters in a string
*
* Description: Example of counting the letters in a string in C.
*
* YouTube Lesson: https://www.youtube.com/watch?v=JXL8NYoVv6U
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_letters(char *s);
int main()
{
// test the function
char s[] = "A string with some letters 123456789 !@#%^&*(";
int result = count_letters(s);
printf("letter count: %d\n", result);
return 0;
}
// returns the number of letters in string s
int count_letters(char *s)
{
int length = strlen(s);
int count = 0;
// check each character in the string, increment count each time a letter is
// encountered (isalpha() returns true if the char is a letter)
for (int i = 0; i < length; i++)
if (isalpha(s[i])) count++;
return count;
}