C程序设计 (第四版) 谭浩强 习题6.10
习题 6.10 有一篇文章,共有3行文字,每行有80个字符。要求分别统计出其中英文大写字母、小写字母、数字、空格以及其他字符的个数。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:使用数组
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[3][80];
int upperCaseLetter, lowerCaseLetter, number, space, others;
printf("Enter 3 lines strings:\n");
for(int i = 0; i < 3; i++){
printf("Line %d: ", i + 1);
gets(str[i]);
}
for(int i = 0; i < 3; i++){
upperCaseLetter = 0;
lowerCaseLetter = 0;
number = 0;
space = 0;
others = 0;
for(int j = 0; str[i][j] != '\0'; j++){
if(str[i][j] >= 'A' && str[i][j] <= 'Z'){
upperCaseLetter++;
}
else if(str[i][j] >= 'a' && str[i][j] <= 'z'){
lowerCaseLetter++;
}
else if(str[i][j] >= '0' && str[i][j] <= '9'){
number++;
}
else if(str[i][j] == ' ' || str[i][j] == '\t'){
space++;
}
else{
others++;
}
}
printf("\nLine %d:\nUpperCase Letter = %d\nLowerCase Letter = %d\nNumber = %d\nSpace = %d\nOthers = %d\n\n", i + 1, upperCaseLetter, lowerCaseLetter, number, space, others);
}
system("pause");
return 0;
}
方法2:指针和函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void initialStr(char ***str, int n){
*str = (char**)malloc(n * sizeof(char*));
for(int i = 0; i < n; i++){
(*str)[i] = (char*)malloc(80 * sizeof(char));
}
}
void inputStr(char **str, int n){
printf("Enter %d lines strings:\n", n);
for(int i = 0; i < 3; i++){
printf("Line %d: ", i + 1);
gets(str[i]);
}
}
void countStr(char **str, int n){
for(int i = 0; i < 3; i++){
int count[5] = {0};
for(int j = 0; str[i][j] != '\0'; j++){
if(str[i][j] >= 'A' && str[i][j] <= 'Z'){
count[0]++;
}
else if(str[i][j] >= 'a' && str[i][j] <= 'z'){
count[1]++;
}
else if(str[i][j] >= '0' && str[i][j] <= '9'){
count[2]++;
}
else if(str[i][j] == ' ' || str[i][j] == '\t'){
count[3]++;
}
else{
count[4]++;
}
}
printf("\nLine %d:\n", i + 1);
for(int k = 0; k < 5; k++){
switch(k){
case 0: printf("UpperCase Letter = %d\n", count[k]); break;
case 1: printf("LowerCase Letter = %d\n", count[k]); break;
case 2: printf("Number = %d\n", count[k]); break;
case 3: printf("Space = %d\n", count[k]); break;
case 4: printf("Others = %d\n\n", count[k]); break;
default: break;
}
}
}
}
void freeStr(char ***str, int n){
for(int i = 0; i < n; i++){
free((*str)[i]);
}
free(*str);
}
int main()
{
char **str = NULL;
initialStr(&str, 3);
inputStr(str, 3);
countStr(str, 3);
freeStr(&str, 3);
system("pause");
return 0;
}