Example:
Input string: I love programming.
Output: Alphabets = 16
Digits = 0
Special character = 3
Total length = 19
Required knowledge
Basic C programming, Loop, StringIt would be really easy to code solution of this program if you already know how to check whether a character is alphabets, digits or special character. As logic to this program is similar to mentioned program. What we need to do in extra is run a loop from 0 to end of the string.
Program to count number of alphabets, digits and special characters in string
/**
* C program to count total number of alphabets, digits and special characters in a string
*/
#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the string
int main()
{
char string[MAX_SIZE];
int alphabets, digits, others, i;
alphabets = digits = others = i = 0;
/* Reads a string from user */
printf("Enter any string : ");
gets(string);
/*
* Checks each character of string
*/
while(string[i]!='\0')
{
if((string[i]>='a' && string[i]<='z') || (string[i]>='A' && string[i]<='Z'))
{
alphabets++;
}
else if(string[i]>='0' && string[i]<='9')
{
digits++;
}
else
{
others++;
}
i++;
}
printf("Alphabets = %d\n", alphabets);
printf("Digits = %d\n", digits);
printf("Special characters = %d\n", others);
return 0;
}
Output
Enter any string : Today is 12 november.
Alphabets = 15
Digits = 2
Special characters = 4
Alphabets = 15
Digits = 2
Special characters = 4
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find length of a string.
- C program to copy one string to another string.
- C program to concatenate two strings.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a given string.
- C program to check whether a string is palindrome or not.
- C program to count number of vowels and consonants in a string.
- C program to find total number of words in a string.