Chương trình đếm số lượng chữ in hoa, in thường, số, khoảng trắng và ký tự đặc biệt trong một chuỗi nhập từ bàn phím.
Code
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int upper = 0, lower = 0, number = 0, special = 0, whitespace = 0;
int i;
printf("Nhap chuoi: ");
fgets(str, sizeof(str), stdin); // an toan hon gets()
// Loai bo ky tu newline neu co
str[strcspn(str, "\n")] = '\0';
for (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')
number++;
else if (str[i] == ' ')
whitespace++;
else
special++;
}
printf("Chu in hoa: %d\n", upper);
printf("Chu in thuong: %d\n", lower);
printf("So: %d\n", number);
printf("Khoang trang: %d\n", whitespace);
printf("Ky tu dac biet: %d\n", special);
return 0;
}
Kết quả mẫu
Nhap chuoi: Hello World 123! Chu in hoa: 2 Chu in thuong: 8 So: 3 Khoang trang: 1 Ky tu dac biet: 1
Cải tiến: Dùng isupper(), islower(), isdigit(), isspace() từ <ctype.h> để code ngắn gọn, hỗ trợ locale tốt hơn.