杨宗德:C语言程序如何判断一个字符是字母或数字


  杨宗德:C语言程序如何判断一个字符是字母或数字。字母表中的所有字母(包括计算机键盘上的所有键)都被赋予了一个值,这些字符及其相应的值一起组成了ASCII字符集,该字符集在北美、欧洲和许多讲英语的国家中得到了广泛的使用。

  字母字符被分成大写和小写两组,并按数字顺序排列。有了这种安排,就能很方便地检查一个字符是否是一个字母以及是大写还是小写。下面这段代码说明了如何检查一个字符是否是一个字母:

  int ch ;

  ch=getche() ;

  if((ch>=97) && (ch<=122))

  printf(" %c is a lowercase letter\n" ,ch);

  else if ((ch>=65) && (ch<=90))

  print(" %c is an uppercase letter\n" ,ch);

  else

  printf(" %c is not an alphabet letter\n" ,ch) ;

  在上例中,变量ch的值与十进制值进行比较。当然,它也可以与字符本身进行比较,因为ASCII字符既是按字符顺序定义的,也是按数字顺序定义的。请看下例:

  int ch ;

  ch=getche() ;

  if((ch>='a') && (ch<='z'))

  printf("%c is a lowercase letter\n" ,ch);

  else if ((ch>='A') && (ch<='Z'))

  print(" %c is a uppercase letter\n" ,ch);

  else

  printf(" %c is not an alphabet letter\n" ,ch);

  你可以随便选择一种方法在程序中使用。但是,后一种方法的可读性要好一些,因为你很难记住ASCII码表中每个字符所对应的十进制值。

  怎样判断一个字符是否是一个数字?

  在ASCII码表中,数字字符所对应的十进制值在48到57这个范围之内,因此,你可以用如下所示的代码来检查一个字符是否是一个数字:

  int ch ;

  ch=getche() ;

  if((ch>=48) && (ch<=57))

  printf(" %c is a number character between 0 and 9\n" ,ch) ;

  else

  printf(" %c is not a number\n" ,ch) ;

  与20.18相似,变量ch也可以和数字本身进行比较:

  int ch ;

  ch=getche () ;

  if((ch>='O') && (ch<='9'))

  printf(" %c is a number character between 0 and 9\n" ,oh) ;

  else

  printf(" %c is not a number~n" ,ch) ;

  同样,选用哪一种方法由你决定,但后一种方法可读性更强。

  杨宗德:C语言程序如何判断一个字符是字母或数字,就介绍到这里,要了解更多程序开发的课程,就来良师益友网杨宗德程序开发·精讲堂。