1160: 零起点学算法67——统计字母数字等个数

绝地灬酷狼 2023-01-12 10:17 226阅读 0赞

Description

输入一串字符,统计这串字符里的字母个数,数字个数,空格字数以及其他字符(最多不超过100个字符)

Input

多组测试数据,每行一组

Output

每组输出一行,分别是字母个数,数字个数,空格字数以及其他字符个数

" class="reference-link">Sample Input 5f8f312f51791b8bb0ed0ae07c2ffa43.gif

  1. I am a student in class 1.
  2. I think I can!

Sample Output

  1. 18 1 6 1
  2. 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

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<string.h>
  4. using namespace std;
  5. int main()
  6. {
  7. char a[300];
  8. while(gets(a)!=NULL)
  9. {
  10. int n=strlen(a);
  11. int word=0;
  12. int num=0;
  13. int space=0;
  14. int other=0;
  15. for(int i=0;i<n;i++)
  16. {
  17. if((a[i]<='z'&&a[i]>='a')||(a[i]>='A'&&a[i]<='Z'))
  18. word++;
  19. else if(a[i]<='9'&&a[i]>='0')
  20. num++;
  21. else if(a[i]==' ')
  22. space++;
  23. else
  24. other++;
  25. }
  26. cout<<word<<" "<<num<<" "<<space<<" "<<other<<endl;
  27. }
  28. }

同时,根据这一题的提示可以学习到不需要使用strlen来获取字符串的长度。因为gets(a)函数会自动在字符串的末尾加上’\n’,所以循环条件直接写成a[i]!=’\n’即可,修改如下

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<string.h>
  4. using namespace std;
  5. int main()
  6. {
  7. char a[300];
  8. while(gets(a)!=NULL)
  9. {
  10. int word=0;
  11. int num=0;
  12. int space=0;
  13. int other=0;
  14. for(int i=0;i!='\n';i++)
  15. {
  16. if((a[i]<='z'&&a[i]>='a')||(a[i]>='A'&&a[i]<='Z'))
  17. word++;
  18. else if(a[i]<='9'&&a[i]>='0')
  19. num++;
  20. else if(a[i]==' ')
  21. space++;
  22. else
  23. other++;
  24. }
  25. cout<<word<<" "<<num<<" "<<space<<" "<<other<<endl;
  26. }
  27. }

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读