Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Đếm chữ cái, chữ số, ký tự đặc biệt trong chuỗi bằng C


Logic để tìm chữ cái, chữ số, ký tự đặc biệt:

for(number=0;string[number]!='\0';number++) {// vòng lặp đến cuối chuỗi     if(string[number]>='a'&&string[number]<='z'||string[number]>='A'&&string[number]<='Z') //kiểm tra chữ cái{         alphabets=alphabets+1; //đếm chữ cái         //alphabets++;     }     else if(string[number]>='0'&&string[number]<='9'){ //kiểm tra số         digits=digits+1; //đếm số         //digits++;     } else {         special=special+1; //đếm ký tự đặc biệt         //special++;     } }

Chương trình xác định tổng số chữ cái, chữ số, ký tự đặc biệt trong chuỗi:

Ví dụ

#include<stdio.h> #include<ctype.h> void main(){     //Khai báo biến đếm, chuỗi//     int number;     char string[50];     int alphabets=0;     int digits=0;     int special=0;     //Nhập từ người dùng//     printf("Enter the string :");     gets(string);     for(number=0;string[number]!='\0';number++){         if(string[number]>='a'&&string[number]<='z'||string[number]>='A'&&string[number]<='Z'){             alphabets=alphabets+1;             //alphabets++;         }         else if(string[number]>='0'&&string[number]<='9'){             digits=digits+1;             //digits++;         }         else{             special=special+1;             //special++;         }     }     //In kết quả//     printf("The number of alphabets in the string is : %d\n",alphabets);     printf("The number of digits in the string is : %d\n",digits);     printf("The number of special characters in the string is : %d\n",special); }

Kết quả

Enter the string :The number of alphabets in the string is : 0 The number of digits in the string is : 0 The number of special characters in the string is : 1