当前位置:网站首页>PTA习题 分类统计字符个数(C)

PTA习题 分类统计字符个数(C)

2022-08-09 10:58:00 拾荒大妈

本题要求实现一个函数,统计给定字符串中英文字母、空格或回车、数字字符和其他字符的个数。
函数接口定义:
void StringCount( char s[] );
其中 char s[] 是用户传入的字符串。函数StringCount须在一行内按照

letter = 英文字母个数, blank = 空格或回车个数, digit = 数字字符个数, other = 其他字符个数的格式输出。

裁判测试程序样例:

#define MAXS 15

void StringCount( char s[] );
void ReadString( char s[] ); /* 由裁判实现,略去不表 */

int main()
{
    char s[MAXS];

    ReadString(s);
    StringCount(s);

    return 0;
}

/* Your function will be put here */
在这里插入代码片

输入样例:


aZ &
09 Az

输出样例:

letter = 4, blank = 3, digit = 2, other = 1

思路
通过使用strlen首先判断字符串中的字符个数,然后依次判断字符串中字符的类型。(也可以通过s[i]==’\0’来判断字符串是否已经结束)

void StringCount( char s[] )
{
    
int letter=0;
    int blank=0,digit=0,other=0;
    int n=strlen(s);
    int i=0;
for(;i<n;i++)
  {
    
if((s[i]>='A'&&s[i]<='Z')||(s[i]>='a'&&s[i]<='z'))
   letter++;
      else if(s[i]>='0'&&s[i]<='9') digit++;
      else if(s[i]==' '||s[i]=='\n')blank++;
      else other++;
  }
    printf("letter = %d, blank = %d, digit = %d, other = %d",letter,blank,digit, other);

}

在这里插入图片描述

做题时遇到的问题

1.应该是’A’,而自己做题时写成"A"
2. 题目中blank的个数是空格和回车的个数之和

原网站

版权声明
本文为[拾荒大妈]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_46127986/article/details/107740752