习题 5.4 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符个数。
2017-08-08 10:34
411 查看
C程序设计 (第四版) 谭浩强 习题5.4 个人设计
习题 5.4 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符个数。
代码块:方法1:(利用while循环结构)
#include <stdio.h> int main() { char c; int letter=0, space=0, number=0, others=0; //定义字母,空格,数字,其他字符并初始化 printf("Please enter character: "); //判断输入的字符 while ((c=getchar()) != '\n'){ if ((c>='a' && c<='z') || (c>='A' && c<='Z')) letter++; else if (c==' ' || c=='\t') space++; else if (c>='0' && c<='9') number++; else others++; } printf("Letter=%d, Space=%d, Number=%d, Others=%d\n", letter, space, number, others); //输出结果 return 0; }
方法2:(利用for循环结构)
#include <stdio.h> int main() { char c; printf("Please enter character: " 4000 ); for (int l=0, sp=0, n=0, oth=0; (c=getchar())!='\n';){ if ((c>='a' && c<='z') || (c>='A' && c<='Z')) l++; else if (c==' ' || c=='\t') sp++; else if (c>='0' && c<='9') n++; else oth++; } printf("Letter=%d, Space=%d, Number=%d, Others=%d\n", l, sp, n, oth); return 0; }
方法3:(利用函数的模块化设计)
#include <stdio.h> void input(); //定义输入函数 int letter(char s[]); //定义字母统计函数 int space(char s[]); //定义空格统计函数 int number(char s[]); //定义数字统计函数 int others(char s[]); //定义其他字符统计函数 char ch[20]; //定义全局变量字符数组 int main() { input(); //调用输入函数 printf("Letter=%d, Space=%d, Number=%d, Others=%d\n", letter(ch), space(ch), number(ch), others(ch)); return 0; } //输入函数 void input() { char c; printf("Please enter character: "); for (int i=0; (c=getchar())!='\n'; ch[i++]=c); } //字母统计函数 int letter(char s[]) { for (int i=0, l=0; s[i]!='\0'; (s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z') ? l++, i++ : i++); return l; } //空格统计函数 int space(char s[]) { for (int i=0, sp=0; s[i]!='\0'; s[i]==' ' || s[i]=='\t' ? sp++, i++ : i++); return sp; } //数字统计函数 int number(char s[]) { for (int i=0, n=0; s[i]!='\0'; s[i]>='0' && s[i]<='9' ? n++, i++ : i++); return n; } //其他字符统计函数 int others(char s[]) { for (int i=0, oth=0; s[i]!='\0'; i++); return oth = i-letter(s)-space(s)-number(s); }
相关文章推荐
- [c++]输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。(写的代码有疑惑,求解求教)
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数【while循环】
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数
- c语言:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
- 输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
- 输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
- 华为oj_输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行文字,分别统计其中英文字母,空格,数字和其他字符
- 输入一行字符,分别统计出其中英文字母 空格 数字 和其他字符的个数
- 输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数
- 50道编程题之07:输入一行字符,分别统计出其中的英文字母,空格,数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数。。。
- 输入一行字符,分别统计出其中的英文字母、空格、数字、和其他字符的个数
- 输入一行字符,分别统计出其中的英文字母,空格,数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母 空格 数字和其他字符的个数
- 输入一行字符 分别统计其中英文字母 空格 数字 和其他字符的个数