c#编程,在键盘上输入一串字符,统计字母、数字和其他字符的个数。

如题所述

// 在键盘上输入一串字符,统计字母、数字和其他字符的个数。

using System;

class Program
{
  static void Main()
  {
    Console.Write("请输入一串字符: ");
    string s = Console.ReadLine();
    int alpha = 0, digit = 0, other = 0;
    foreach (char c in s)
    {
      if      (Char.IsLetter(c)) ++alpha;
      else if (Char.IsDigit (c)) ++digit;
      else ++other;
    }
    Console.WriteLine("字母{0}个,数字{1}个,其他字符{2}个", alpha, digit, other);
  }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-06-26
1getchar
#include <stdio.h>
int main()
{
int c=0,s=0,n=0, o=0;
char i;
while((i=getchar())!='\n')
{
if((i>='A'&&i<='Z') || (i>='a'&&i<='z') )
c++;
else if(i>='0'&&i<='9')
n++;
else if(i == ' ')
s++;
else o++;
}
printf("英文字母 %d,空格 %d,数字 %d, 其他字符 %d\n", c, s, n, o);
return 0;
}
2scanf
#include <stdio.h>
int main()
{
int c=0,s=0,n=0, o=-1;
char i='\0';
while(i!='\n')
{ scanf("%c",&i);
if((i>='A'&&i<='Z') || (i>='a'&&i<='z') )
c++;
else if(i>='0'&&i<='9')
n++;
else if(i == ' ')
s++;
else o++;
}
printf("英文字母 %d,空格 %d,数字 %d, 其他字符 %d\n", c, s, n, o);
return 0;
}
gets()
# include <stdio.h>
int main(void)
{
int a[4]={0},i=0;
char str[80];
printf("请输入一行字符:\n");
gets(str);
while (str[i] != 0)
{
if (str[i]>='a' && str[i]<='z' || (str[i]>='A' && str[i]<='Z'))
a[0]++;
else if (str[i]>='0' && str[i]<='9')
a[1]++;
else if (str[i] == ' ')
a[2]++;
else
a[3]++;
i++;
}
printf("字母:%d\n数字:%d\n空格:%d\n其她:%d\n",a[0],a[1],a[2],a[3]);
return 0;

}
4指针和gets
#include<stdio.h>
int main()
{
int a=0,b=0,c=0,d=0,e=0;
char *p,str[80];
p=str;
gets(str);
while(*p)
if(*p>='A' && *p <='Z')
{a++;p++;}
else if(*p>='a' && *p <='z')
{b++;p++;}
else if(*p==' ')
{c++;p++;}
else if(*p>='0' && *p <='9')
{d++;p++;}
else
{e++;p++;}
printf("大写%d 小写%d 空格%d 数字%d 其它%d 英文%d\n",a,b,c,d,e,a+b);
return 0;
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网