Assert
errno.h

ctype.h

风中纸页 posted @ 2008年12月21日 19:00 in C标准库学习笔记 , 1241 阅读
转贴请保留本文作者及文章地址

本篇小文来讲述一下ctype.h中提供的函数有哪些以及应用场合和实现。并提出的我的疑问。

为什么有这个库函数族?
在我们写程序的时候经常会碰到对于英文字母,阿拉伯数字等等的判断,这样C库中的ctype.h就为我们提供这些功能。当然根据有些特殊的编码C库还提供了wctype.h的另一组库函数。这些函数都是以is开始的。
都提供了我们什么功能?

int isalnum(int c);

函数判断(大小写)字符以及阿拉伯数字。

int isalpha(int c);
函数判断(大小写)字符

int isblank(int c)
判断空字符,包括空格和制表符
int iscntrl(int c);
函数判断是不是控制字符。控制字符包括: BEL BS CR FF HT NL VT

int isdigit(int c);
函数判断是不是阿拉伯数字:0 1 2 3 4 5 6 7 8 9

int isgraph(int c);

函数判断是不是可打印字符(不包含空格)

int islower(int c);

函数判断是不是小写字符


int isprint(int c);
函数判断是不是可打印字符(包含空格)

int ispunct(int c);

函数判断是不是标点字符:! " # % & ' ( ) ; < = > ? [ \ ] * + , - . / : ^ _ { | } ~

int isspace(int c);

函数CR FF HT NL VT space

int isupper(int c);
函数判断如果不是如下字符则返回0
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

int isxdigit(int c);
函数判断如果不是如下字符则返回0
0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

由于(仅)涉及到ascii字符的处理,我觉得有必要把ascii码表分区复习一下:

ascii码表简单说就是把char能表示的字符在一个表格中描述出来。用7bit表示的128个字符

接下来我们可以看一下ctype.c中的处理部分,这里我有对locale的内容的疑问,有哪位明白请指点指点。(我仅仅知道locale是用做区域设置,但没有了解过locale的根本原理。

# define isalnum(c)     __isctype((c), _ISalnum)
# define isalpha(c)     __isctype((c), _ISalpha)
# define iscntrl(c)     __isctype((c), _IScntrl)
# define isdigit(c)     __isctype((c), _ISdigit)
# define islower(c)     __isctype((c), _ISlower)
# define isgraph(c)     __isctype((c), _ISgraph)
# define isprint(c)     __isctype((c), _ISprint)
# define ispunct(c)     __isctype((c), _ISpunct)
# define isspace(c)     __isctype((c), _ISspace)
# define isupper(c)     __isctype((c), _ISupper)
# define isxdigit(c)    __isctype((c), _ISxdigit)
 

这里根据不同的类型使用了不同的mask值。

--isctype看起来就是从当前LC_TYPE指定的

int
__isctype (ch, mask)
     int ch;
     int mask;
{
  return (((uint16_t *) _NL_CURRENT (LC_CTYPE, _NL_CTYPE_CLASS) + 128)
          [(int) (ch)] & mask);
}

{
  _ISupper = _ISbit (0),        /* UPPERCASE.  */
  _ISlower = _ISbit (1),        /* lowercase.  */
  _ISalpha = _ISbit (2),        /* Alphabetic.  */
  _ISdigit = _ISbit (3),        /* Numeric.  */
  _ISxdigit = _ISbit (4),       /* Hexadecimal numeric.  */
  _ISspace = _ISbit (5),        /* Whitespace.  */
  _ISprint = _ISbit (6),        /* Printing.  */
  _ISgraph = _ISbit (7),        /* Graphical.  */
  _ISblank = _ISbit (8),        /* Blank (usually SPC and TAB).  */
  _IScntrl = _ISbit (9),        /* Control character.  */
  _ISpunct = _ISbit (10),       /* Punctuation.  */
  _ISalnum = _ISbit (11)        /* Alphanumeric.  */
}

#if __BYTE_ORDER == __BIG_ENDIAN
#define _ISbit(bit)     (1 << (bit))
#else /* __BYTE_ORDER == __LITTLE_ENDIAN */
#define _ISbit(bit)     ((bit) < 8 ? ((1 << (bit)) << 8) : ((1 << (bit)) >> 8))
#endif

这里是我比较困惑的地方,这种mask的是如何定义的?

__isctype又是为何这样实现的?

小结一下,虽然从代码中没有看出什么端倪,但是我明确了这些库函数的使用,以及彼此之间的区别。似乎还和locale有关,这个还是需要进一步了解一下的。

  • 无匹配

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter