C 练习实例17
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为'\n'。
实例
// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鸟教程. All rights reserved.
#include <stdio.h>
int main() {
char c;
int letterCount = 0, spaceCount = 0, digitCount = 0, otherCount = 0;
printf("请输入一些字符:\n");
while ((c = getchar()) != '\n') {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letterCount++;
} else if (c >= '0' && c <= '9') {
digitCount++;
} else if (c == ' ') {
spaceCount++;
} else {
otherCount++;
}
}
printf("字母 = %d, 数字 = %d, 空格 = %d, 其他 = %d\n", letterCount, digitCount, spaceCount, otherCount);
return 0;
}
以上实例输出结果为:
请输入一些字母: www.runoob.com 123 字母=12,数字=3,空格=1,其他=2
C 语言经典100例
学工
121***1688@qq.com
参考方法:
#include <stdio.h> int main() { int c,i=0, j=0, k=0, l=0; printf("请输入一些字母:\n"); while(c!='\n') { c=getchar(); if( c>96 && c<123 )i++; if( c>64 && c<91 )i++; if( c>47 && c<58 )j++; if( c==32 )k++; l++; // 会多计算一个Eenter,故需在统计时减一; } printf("英文字母%d个,数字%d个,空格%d个,其它字符%d个\n",i,j,k,l-i-j-k-1); }学工
121***1688@qq.com
HIT_CCC
117***2963@qq.com
参考方法:
#include<stdio.h> int main(void) { char ch; int alpha,num,space,others; alpha = num = space = others = 0; printf("请输入一些字母:\n"); while((ch = getchar()) != '\n') { if((ch >= 'a' && ch <= 'z')||(ch >='A' && ch <='Z')) alpha++; else if(ch >= '0' && ch <= '9') num++; else if(ch == ' ') space++; else others++; } printf("字母=%d,数字=%d,空格=%d,其他=%d",alpha,num,space,others); return 0; }HIT_CCC
117***2963@qq.com
ronnyz
221***8677@qq.com
参考方法:
#include <stdio.h> #include <ctype.h> #define N 100 int main(){ char c1; char str[N]; int lower=0,upper=0,space=0,digit=0,other=0; gets(str); int i=0; while(str[i]){ c1=str[i]; i++; if(islower(c1)) lower++; else if(isupper(c1)) upper++; else if(isspace(c1)) space++; else if(isdigit(c1)) digit++; else other++; } printf("大写字母=%d,小写字母=%d,数字=%d,空格=%d,其他=%d\n",upper,lower,digit,space,other); return 0; }ronnyz
221***8677@qq.com
R6bandito
334***4569@qq.com
参考方法:
#include <stdio.h> #include <string.h> #include <ctype.h> // 用于isspace函数 #define MAX_RANGE 65535 int main() { char s[MAX_RANGE]; size_t i = 0; // 定义四个变量分别作为对应的计数器 unsigned int count_Num = 0; unsigned int count_Char = 0; unsigned int count_Space = 0; unsigned int count_Other = 0; printf("请输入一个长度不大于%d的字符串\n", MAX_RANGE); if (fgets(s, sizeof(s), stdin) == NULL) { fprintf(stderr, "读取输入失败。\n"); return 1; } // 去除fgets读取的换行符 s[strcspn(s, "\n")] = 0; for (i = 0; s[i] != '\0'; i++) { if (isdigit((unsigned char)s[i])) { count_Num++; } else if (isalpha((unsigned char)s[i])) { count_Char++; } else if (isspace((unsigned char)s[i])) { count_Space++; } else { count_Other++; } } printf("空格符:%u个 英文字符:%u个 数字:%u个 其它字符:%u个\n", count_Space, count_Char, count_Num, count_Other); return 0; }R6bandito
334***4569@qq.com