C //习题 7.9 编写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格、和其他字符的个数,在主函数中输入字符串以及输出上述的结果。

本文提供两种方法实现C语言中字符串的分析,统计其中字母、数字、空格及其他字符的数量。方法一采用固定大小的数组进行计数,而方法二则通过指针及动态分配内存实现相同功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值