统计字符串中字母、数字、空格和其它字符的个数
编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其它字符的个数。在主函数中输入字符串(例如The 2+3=7 is wrong!),调用该函数,然后由主函数输出统计结果(字母10个、数字3个、空格3个、其它字符3个)。
1.使用全局变量
//使用全局变量统计字符串中元素个数
#include<stdio.h>
#include<stdlib.h>
#define N 999
int number=0,character=0,space=0,others=0;
void count(char str[]){
for(int i=0;str[i]!= ;i++){
if(str[i]>0&&str[i]<9){
number++;
}
else if((str[i]>a&&str[i]<z)||(str[i]>A&&str[i]<Z)){
character++;
}
else if(str[i]==32){ //32对照ascii码中的空格
space++;
}
else others++;
}
}
int main(void){
char str[N];
gets(str);
count(str);
printf("number=%d
character=%d
space=%d
others=%d",number,character,space,others);
}
2.不使用全局变量
//不使用全局变量统计字符串中元素的个数
#include<stdio.h>
#include <stdlib.h>
#define N 999
void count(char str[],int a[]){
for(int i=0;str[i]!= ;i++){
if(str[i]>0&&str[i]<9){
a[0]++;
}
else if((str[i]>a&&str[i]<z)||(str[i]>A&&str[i]<Z)){
a[1]++;
}
else if(str[i]==32){ //32对照ascii码中的空格
a[2]++;
}
else a[3]++;
}
}
int main(void){
char str[N];
int a[4]={0};
gets(str);
count(str,a);
printf("number=%d
character=%d
space=%d
others=%d
",a[0],a[1],a[2],a[3]);
}
