1160: 零起点学算法67——统计字母数字等个数
Description
输入一串字符,统计这串字符里的字母个数,数字个数,空格字数以及其他字符(最多不超过100个字符)
Input
多组测试数据,每行一组
Output
每组输出一行,分别是字母个数,数字个数,空格字数以及其他字符个数
" class="reference-link">Sample Input 
I am a student in class 1.
I think I can!
Sample Output
18 1 6 1
10 0 3 1
HINT
char str[100];//定义字符型数组
while(gets(str)!=NULL)//多组数据
{
//输入代码
for(i=0;str[i]!=’\0’;i++)//gets函数自动在str后面添加’\0’作为结束标志
{
//输入代码
}
//字符常量的表示,
‘a’表示字符a;
‘0’表示字符0;
//字符的赋值
str[i]=’a’;//表示将字符a赋值给str[i]
str[i]=’0’;//表示将字符0赋值给str[i]
}
Source
零起点学算法
Code
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char a[300];
while(gets(a)!=NULL)
{
int n=strlen(a);
int word=0;
int num=0;
int space=0;
int other=0;
for(int i=0;i<n;i++)
{
if((a[i]<='z'&&a[i]>='a')||(a[i]>='A'&&a[i]<='Z'))
word++;
else if(a[i]<='9'&&a[i]>='0')
num++;
else if(a[i]==' ')
space++;
else
other++;
}
cout<<word<<" "<<num<<" "<<space<<" "<<other<<endl;
}
}
同时,根据这一题的提示可以学习到不需要使用strlen来获取字符串的长度。因为gets(a)函数会自动在字符串的末尾加上’\n’,所以循环条件直接写成a[i]!=’\n’即可,修改如下
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char a[300];
while(gets(a)!=NULL)
{
int word=0;
int num=0;
int space=0;
int other=0;
for(int i=0;i!='\n';i++)
{
if((a[i]<='z'&&a[i]>='a')||(a[i]>='A'&&a[i]<='Z'))
word++;
else if(a[i]<='9'&&a[i]>='0')
num++;
else if(a[i]==' ')
space++;
else
other++;
}
cout<<word<<" "<<num<<" "<<space<<" "<<other<<endl;
}
}
还没有评论,来说两句吧...