C程序设计 (第四版) 谭浩强 习题7.9
习题 7.9 编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格、和其他字符的个数,在主函数中输入字符串以及输出上述的结果。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:使用数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 80
void counter(char str[], int count[]){
int len = strlen(str);
for(int i = 0; i < len; i++){
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')){
count[0]++;
}
else if(str[i] >= '0' && str[i] <= '9'){
count[1]++;
}
else if(str[i] == ' ' || str[i] == '\t'){
count[2]++;
}
else{
count[3]++;
}
}
}
int main(){
char str[N];
int count[4] = {0}; //统计数组
printf("Enter string: ");
gets(str);
counter(str, count);
printf("Letter = %d, Number = %d, Space = %d, Others = %d\n", count[0], count[1], count[2], count[3]);
system("pause");
return 0;
}
方法2:使用指针、动态分配内存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 80
void inputStr(char *str){
printf("Enter string: ");
gets(str);
}
void counter(char *str, int *count){
int len = strlen(str);
for(int i = 0; i < 4; i++){
count[i] = 0;
}
for(int i = 0; i < len; i++){
if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')){
count[0]++;
}
else if(str[i] >= '0' && str[i] <= '9'){
count[1]++;
}
else if(str[i] == ' ' || str[i] == '\t'){
count[2]++;
}
else{
count[3]++;
}
}
}
int main(){
char *str = (char*)malloc(N * sizeof(char));
int *count = (int*)malloc(4 * sizeof(int));
inputStr(str);
counter(str, count);
printf("Letter = %d, Number = %d, Space = %d, Others = %d\n", count[0], count[1], count[2], count[3]);
system("pause");
return 0;
}