首页 > 试题广场 >

分类统计字符个数:输入一行字符,统计出其中的英文字母、空格、

[问答题]

分类统计字符个数:输入一行字符,统计出其中的英文字母、空格、数字和其他字符的个数。试编写相应程序。

推荐
#include <stdio.h>
int main(void)
{
char c;
int blank, digit, letter, other;
c = getchar();
blank = digit = letter = other = 0;
while(c != '\n'){
if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
letter++;
else if(c >= '0' && c <= '9')
digit++;
else if(c == ' ')
blank++;
else
other++;
c = getchar();
}
printf("letter = %d, blank = %d, digit = %d, other = %d\n", letter, blank, digit, other);
return 0;
}

发表于 2018-05-06 21:30:15 回复(0)
#define _CRT_SECURE_NO_WARNINGS    
//#include <stdlib.h> 
#include <stdio.h>
//#include<malloc.h>
//#include<math.h>
//#include <string.h>
#include <ctype.h> //字符处理 

int main() {
    char input_string[100];
    int letter_count = 0, space_count = 0, digit_count = 0, other_count = 0;

    printf("请输入一行字符:");
    fgets(input_string, 100, stdin);

    for (int i = 0; input_string[i] != '\0'; i++) {
        if (isalpha(input_string[i])) {
            letter_count++;
        }
        else if (isspace(input_string[i])) {
            space_count++;
        }
        else if (isdigit(input_string[i])) {
            digit_count++;
        }
        else {
            other_count++;
        }
    }

    printf("英文字母个数:%d\n", letter_count);
    printf("空格个数:%d\n", space_count);
    printf("数字个数:%d\n", digit_count);
    printf("其他字符个数:%d\n", other_count);

    return 0;
}


    










发表于 2023-07-18 10:55:07 回复(0)
为什么这样子写不行呢?
#include<stdio.h>
int main(void)
{
	int in,blank,digit,other;
	char ch;
	scanf("%c",&ch);
	while(ch!='\n'){
		switch(ch){
			case(ch>'a' && ch<'z'):
				in++;
				break;
			case(ch>'A'&&ch<'Z'):
				in++;
				break;
			case' ':
				blank++;
				break;
			case'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':
				digit++;
				break;
			default:
				other++;
				break;
		}
		scanf("%c",&ch);
	}
	printf("英文字符为%d个,空格为%d个,数字为%d个,其他字符为%d个",in,blank,digit,other);
	return 0;
}

发表于 2022-02-28 21:33:47 回复(0)
# include <stdio.h>
# include <iostream>
# include <string.h>

using namespace std;

int main()
{
    char ch;
    
    int a,b,c,d;
 
    a=b=c=d=0;
    ch=getchar();
    while(ch != '\n')
    {
       if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
           a++;
       else if(ch == ' ')
           b++;
       else if(ch>=0&&ch<=0)
           c++;
       else
           d++;

       ch=getchar();
    }
    printf("letter=%d,blank=%d,digit=%d,other=%d\n",a,b,c,d);
}

发表于 2019-07-16 22:28:10 回复(0)