Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count spaces, uppercase and lowercase in a sentence using C
In C programming, counting different types of characters in a string is a common task. This involves analyzing each character to determine if it's uppercase, lowercase, a digit, whitespace, or a special character.
Syntax
for (int i = 0; str[i] != '\0'; i++) {
// Check character type using ASCII values
if (str[i] >= 'A' && str[i] <= 'Z') // Uppercase
else if (str[i] >= 'a' && str[i] <= 'z') // Lowercase
else if (str[i] >= '0' && str[i] <= '9') // Digits
else if (str[i] == ' ') // Whitespace
}
Example: Character Classification
This example demonstrates how to count spaces, uppercase letters, lowercase letters, digits, and special characters in a string −
#include <stdio.h>
int main() {
char str[100];
int upper = 0, lower = 0, digits = 0, spaces = 0, special = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
upper++;
}
else if (str[i] >= 'a' && str[i] <= 'z') {
lower++;
}
else if (str[i] >= '0' && str[i] <= '9') {
digits++;
}
else if (str[i] == ' ') {
spaces++;
}
else if (str[i] != '
') {
special++;
}
}
printf("Uppercase letters: %d
", upper);
printf("Lowercase letters: %d
", lower);
printf("Digits: %d
", digits);
printf("Spaces: %d
", spaces);
printf("Special characters: %d
", special);
return 0;
}
Enter a string: Hello World 123! Uppercase letters: 2 Lowercase letters: 8 Digits: 3 Spaces: 1 Special characters: 1
Key Points
- We use
fgets()instead ofgets()for safer input handling. - ASCII value ranges: 'A'-'Z' (65-90), 'a'-'z' (97-122), '0'-'9' (48-57).
- The condition
str[i] != 'excludes the newline character from special characters.
' - Each character is checked sequentially using if-else conditions.
Conclusion
Character classification in C uses ASCII value comparisons to categorize each character in a string. This technique is essential for text processing and input validation in C programs.
Advertisements
