编写函数统计字符串中字符的出现次数

首先,我们需要知道字符有哪几种类型

一般可以分为以下三类:

  • 字母
  • 数字
  • 空格和其他字符

而我们的目标是统计输入字符串中这些字符的出现次数,那么该如何统计呢?

一般来说是通过for循环,然后在里面使用if语句限定条件之后找出我们所需要的类型。

字符串不是int arr[ ],所以锁定字符的方式就会用到另一个东西,ASCII码值1如需要观看请看注释

总之从ASCII码值中我们发现了,字母的值范围为65-9097-122,而数字则是48-57,空格为32,剩下的则是其他字符
这样子,我们就找到了限定条件,可以开始编写函数了

//函数部分
void StatCharCount(char str[], int size, int* count1, int* count2, int* count3, int* count4)
{
		if (str[i] >= 65 && str[i] <= 90 || str[i] >= 97 && str[i] <= 122)
			(*count1)++;
		//字母
		else if (str[i] >= 48 && str[i] <= 57)
			(*count2)++;
		//数字
		else if (str[i] == 32)
			(*count3)++;
		//空格
		else
			(*count4)++;
		//其他字符
	}
}
//该函数接收一个字符串作为参数,统计该字符串中字母、数字、空格和其他字符的个数
//在main函数调用该函数,分别打印字母、数字、空格 和 其他字符的出现次数。
int main()
{
	char str[] = "123abc *&";
	int size = sizeof(str) / sizeof(str[0]);
    //计算字符长度
	int count1 = 0;
	int count2 = 0;
	int count3 = 0;
	int count4 = 0;

	StatCharCount(str, size, &count1, &count2, &count3, &count4);//这个里面放的元素是实参
	
	printf("字母:%d\n", count1);
	printf("数字:%d\n", count2);
	printf("空格:%d\n", count3);
	printf("其他字符:%d\n", count4);

	return 0;
}

这段代码写出来后,还有一些需要注意的点,比如:

  1. 要注意这是指针的写法,如果没有学过指针的话很可能一开始就不会把int*和(*count)这些打出来,而是按照普通的int,count来写,那样就错了,函数中的 count1、count2、count3、count4 参数以值传递方式传入函数中,在函数内对它们的值增加并不会影响外部的实际参数,不使用指针就无法更新外部变量的值
  2. 一些同学看到其他字符为3时可能会感到奇怪,因为字符串里明明就只有“*&”两个其他字符,但是他们忽略了"\0"这个字符串结束符

另外,除了用指针的方法,还可以尝试全局变量计数的做法

#include<stdio.h>

int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;

void StatCharCount(char str[], int size)
{
	for (int i = 0; i < size; i++)
	{
		if (str[i] >= 65 && str[i] <= 90 || str[i] >= 97 && str[i] <= 122)
			count1++;
		//字母
		else if (str[i] >= 48 && str[i] <= 57)
			count2++;
		//数字
		else if (str[i] == 32)
			count3++;
		//空格
		else
			count4++;
	}
}

int main()
{
	char str[] = "123abc *&";
	int size = sizeof(str) / sizeof(str[0]);

	StatCharCount(str, size);//这个里面放的元素是实参

	printf("字母:%d\n", count1);
	printf("数字:%d\n", count2);
	printf("空格:%d\n", count3);
	printf("其他字符:%d\n", count4);

	return 0;
}

只需要在头文件下面加上count一类的变量定义即可,那么便可以不使用指针,更方便

另外,我在写代码时还尝试过使用static int,后来发现其只能改变局部变量的生命周期,而无法使其真的跟全局变量一样使用

以上就是我对于这个函数的理解,如有错误,欢迎指正!

  1. 在这里插入图片描述
    在这里插入图片描述在这里插入图片描述
    在这里插入图片描述 ↩︎

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值