C标准库 ctype.h (二) 类型判断函数

ctype.h



#ifndef _CTYPE
#define _CTYPE

/* _Ctype 转换位 */
#define _XA	0x200	/* extra alphabetic */
#define _XS	0x100	/* extra space */
#define _BB	0x80	/* BEL, BS, etc. */
#define _CN	0x40	/* CR, FF, HT, NL, VT */
#define _DI	0x20	/* '0' - '9' */
#define _LO	0x10	/* 'a' - 'z' */
#define _PU	0x08	/* punctuation */
#define _SP	0x04	/* space */
#define _UP	0x02	/* 'A' - 'Z' */
#define _XD	0x01	/* '0' - '9', 'A' - 'F', 'a' - 'f' */

/* 声明外部的 _Ctype 转换表 */
extern const short *_Ctype;

/* 判断是否为小写字母的带参数宏 islower */
#define islower(c) (_Ctype[(int)(c)] & _LO)

// 其余省略 ...

#endif

xctype.c _Ctype 转换表 — ASCII 版


#include <limits.h>
#include <stdio.h>
#include "ctype.h"

#if EOF != -1 || UCHAR_MAX != 255
#error WRONG CTYPE table
#endif

/* 组合位 */ 
#define XDI (_DI|_XD)
#define XLO (_LO|_XD)
#define XUP (_UP|_XD)

/* 转换表 */
static const short ctype_tab[257] = { 0, /* EOF */
	_BB, _BB, _BB, _BB, _BB, _BB, _BB, _BB,
	_BB, _CN, _CN, _CN, _CN, _CN, _BB, _BB,
	_BB, _BB, _BB, _BB, _BB, _BB, _BB, _BB,
	_BB, _BB, _BB, _BB, _BB, _BB, _BB, _BB,
	_SP, _PU, _PU, _PU, _PU, _PU, _PU, _PU,
	_PU, _PU, _PU, _PU, _PU, _PU, _PU, _PU,
	XDI, XDI, XDI, XDI, XDI, XDI, XDI, XDI,
	XDI, XDI, _PU, _PU, _PU, _PU, _PU, _PU,
	_PU, XUP, XUP, XUP, XUP, XUP, XUP, _UP,
	_UP, _UP, _UP, _UP, _UP, _UP, _UP, _UP,
	_UP, _UP, _UP, _UP, _UP, _UP, _UP, _UP,
	_UP, _UP, _UP, _PU, _PU, _PU, _PU, _PU,
	_PU, XLO, XLO, XLO, XLO, XLO, XLO, _LO,
	_LO, _LO, _LO, _LO, _LO, _LO, _LO, _LO,
	_LO, _LO, _LO, _LO, _LO, _LO, _LO, _LO,
	_LO, _LO, _LO, _PU, _PU, _PU, _PU, _BB,
};

const short *_Ctype = &ctype_tab[1];

ctype.c


#include "ctype.h"

// alphanumeric 
int (isalnum)(int c)
{
	return (_Ctype[c] & (_DI | _LO | _UP | _XA));
}

// alphabetic
int (isalpha)(int c)
{
	return (_Ctype[c] & (_LO | _UP | _XA))
}

// control
int (iscntrl)(int c)
{
	return (_Ctype[c] & (_BB | _DI));
}

// digit
int (isdigit)(int c)
{
	return (_Ctype[c] & _DI);
}

// graphic
int (isgraph)(int c)
{
	return (_Ctype[c] & (_DI | _LO | _PU | _UP | _XA));
}

// lowercase
int (islower)(int c)
{
	return (_Ctype[c] & _LO);
}

// printable
int (isprint)(int c)
{
	return (_DI | _LO | _PU | _SP | _UP | _XA);
}

// punctuation
int (ispunct)(int c)
{
	return (_Ctype[c] & _PU);
}

// spacing
int (isspace)(int c)
{
	return (_Ctype[c] & (_CN | _SP | _XS));
}

// 大写字母 uppercase
int (isupper)(int c)
{
	return (_Ctype[c] & _UP);
}

// hexadecimal
int (isxdigit)(int c)
{
	return (_Ctype[c] & _XD);
}

关于

实际上没有什么内容了,只要上一节看懂了,那么这一节只是稍微对照一下用上一节的原理来对照_Ctype 转换表罢了。

如果有疑問还请参见 C标准库 ctype.h (一) _Ctype转换表原理

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s