C语言 给定一个字符串,统计‘a’的个数

这篇博客展示了如何使用C语言统计字符串中字符'a'的个数。通过两个不同的函数实现,一个是直接在main函数中统计,另一个是封装成独立的GetCount函数。代码运行正确,输出结果为字符串'iamastudent'的长度为14,字符'a'出现了2次。

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

给定一个字符串为:i am a student ,统计其中a的个数。

代码如下:

#include<stdio.h>
int  main()
{
	char arr[] = "i am a student";
	int len;
	for(int j = 0; arr[j] != NULL; j++)
	{
	 	len++;
	}
	int count = 0;
	for(int i = 0; i <= len; i++)
	{
		if(arr[i] == 'a')
		{
			count++;
		}
	}
	printf("该数组长度为:%d\n",len);
	printf("a的个数为:%d", count);
	return 0;
}

输出结果为:

该数组长度为:14
a的个数为:2

函数进行封装:

#include<stdio.h>
#include<string.h>
int GetCount(char* str, char aim)
{
	int len = strlen(str);
	int count = 0;
	for(int i = 0; i < len; i++)
	{
		if(str[i] == aim)
		{
			count++;
		}
	}
	return count;
}
int main()
{
	char arr[] = "i am a student";
	int count = GetCount(arr,'a');
	printf("%d\n",strlen(arr));
	printf("%d\n",GetCount(arr,'a'));
	return 0;
}

输出结果为:

14
2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值