C语言 输入一串字符串,并计算字符串中字母、数字、空格以及其他的数量

 

方法一:

知识点:学习使用if嵌套选择结构。

思路:定义字符,判断字符在ASCII码中的大小。

#include<stdio.h>
#include<Windows.h>
#include<time.h>
#include<stdlib.h>
void main()
{
	char c;
	int letters=0,space=0,number=0,others=0;
	printf("please input some characters\n");
	while((c=getchar())!='\n')
	{
		if(c>='a'&&c<='z'||c>='A'&&c<='Z')
		
			letters=letters+1;
		
	
			else if(c==' ')
			{
				space=space+1;
			}
				else if(c>='0'&&c<='9')
				{
					number=number+1;
				}
					else
					{
						others=others+1;
					}
	}
	printf("all in all:char=%d space=%d number=%d others=%d\n",letters,space,number,others);
	system("pause");
}

 

 

方法二:

知识点:使用函数调用计算

思路:定义一个数组,用子函数分别求出字母,数字,空格,其他的数字,具体看源码。

#include<stdio.h>
#include<Windows.h>
#include<string.h>
int zimu(char a[10])
{
	int i,zimu=0;
	for (i = 0; i < 10; i++)
	{
		if ((a[i]>='a'&&a[i]<='z') || (a[i]>='A'&&a[i] <= 'Z'))
			zimu++;
	}
	return (zimu);
}
int number(char a[10])
{
	int i, number=0;
	for (i = 0; i < 10; i++)
	{
		if (a[i]>='0'&&a[i] <= '9')
			number++;
	}
	return (number);
}
int kongge(char a[10])
{
	int i, kongge=0;
	for (i = 0; i < 10; i++)
	{
		if (a[i] == ' ')
			kongge++;
	}
	return(kongge);
}
int others(char a[10],int l)
{
	int i, others=0;
	for (i = 0; i < l; i++)
	{
		if ((a[i]>='a'&&a[i]<='z') || (a[i]>='A'&&a[i] <= 'Z') || (a[i]>='0'&&a[i] <= '9') || (a[i] == ' '))
			continue;
		else
		{
			others++;
		}
	}
	return(others);
}
void main()
{
	char a[10];
	int e, b, c, d,l;
	gets_s(a,10);
	l=strlen(a);
	e = zimu(a);
	b = number(a);
	c = kongge(a);
	d = others(a,l);
	printf("zimu:%d number:%d kongge:%d others:%d",e,b,c,d);
	system("pause");
}

输出结果:

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值