首页 > 试题广场 >

输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的

[问答题]
输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
推荐

#include<stdio.h>

int main( )

{

char c;

int letters=0,space=0,digit=0,other=0;

printf("请输入一行字符:\n”);

while((c=getchar( ))!=’\n’)

{

if(c>=’a’ && c<='z’||c>=’A’&& c<=’Z’)

letters++;

else if(c==' ‘)

space++;

else if(c>=’0’&&c<=’9’)

digit++;

else

other++;

}

printf(“字母数:%d\n空格数:%d\n数字数:%d\n其它字符数:%d\n",letters,space,digit,other);

return 0;

}


发表于 2018-03-25 10:56:13 回复(0)
#include<stdio.h> 
#define N 20	//数组大小 
int main(){
	char a[N];
	int count_char=0,count_null=0,count_num=0,count_other=0;	//分别用来记录英文字母、空格、数字、其他字符的个数 
	printf("请输入一串字符:");
	gets(a); 	//得到键盘输入的字符串,以回车为结束 
	for(int i=0;a[i]!='\0';i++){	//数组中字符串后面那个位置存放的是结束标志'\0' 
		if(a[i]>='A'&&a[i]<='Z'||a[i]>='a'&&a[i]<='z')	//根据ascll码大小进行比较判断 
			count_char++;
		else if(a[i]==' ')
			count_null++;
		else if(a[i]>='0'&&a[i]<='9')
			count_num++;
		else
			count_other++;
	}
	printf("英文字母个数为:%d\n空格个数为:%d\n数字个数为:%d\n他字符个数为:%d",count_char,count_null,count_num,count_other);
	return 0;
}

发表于 2021-01-15 17:59:47 回复(0)
#include <stdio.h>
#include <string.h>
void readline(char s[]){//读行函数是将字符串放入一个字符数组中
 for(int i = 0; ;i ++){
  char c = getchar();//先将读取的字符储存下来,仅用getchar()会丢失掉读到的字符
  if( c == '\n' || c == EOF){//意味着换行或者结束了
   s[i] = 0;//字符串结尾以零结尾
   break;
  }
  s[i] = c;//如果没有结束(上面判断不成立),那这个c储存进来
 }
}
//另外,字符数组每一个单元储存一个字符,并且一段字符串以零结尾,
//当直接调用字符数组名时,就相当于调用了一个字符串,&s[i]表示从i开始
int main(){
 char s[10000];
 readline(s);
 int length = strlen(s);
 s[length] = 0;
 int number = 0;
 int space = 0;
 int word = 0;
 int other = 0;
 for(int i = 0; i < length;i ++){
  if(s[i] >= 48 && s[i] <=57)
   number ++;
  else if(s[i] == ' ')
   space ++;
  else if(s[i] >= 65 && s[i] <=90 || s[i] >= 97 && s[i] <= 122)
   word ++;
  else
   other ++;
 }
 printf("%d %d %d %d\n", number,space,word,other);
}
发表于 2019-12-22 17:31:40 回复(0)
public static void main(String[] args){  int countE=0,countK=0,countS=0,countO=0;
     Scanner scan=new Scanner(System.in);
     System.out.println("please enter String:");
     String str=scan.nextLine();
     char[] ch=str.toCharArray();
     for(int i=0;i<ch.length;i++){   if((ch[i]>='a'&&ch[i]<='z')||(ch[i]>='A'&&ch[i]<='Z')){
              countE++;
              continue;
          }
          if(ch[i])==' '){
              countK++;
              continue;
          }
          if(ch[i]>='0'&&ch[i]<='9'){
              countS++;
              continue;
          }
          else{
               countO++;
               continue;
          }
      }
       System.out.println("英文:" + countE + "   空格:" + countK + "   数学:" + countS + "  其他字符:" + countO);
}


发表于 2019-06-13 13:05:37 回复(0)