您的位置:首页 > 编程语言 > C语言/C++

C语言标准库(1)—#include<ctype.h>

2014-11-25 21:49 381 查看
C语言标准库—#include<ctype.h>
2014/11/25 by jxlijunhao
在这个头文件中包含了对字符测试的函数,如检查一个字符串中某一个字符是否为数字,或者字母等,还包含了字符映射函数,如将大写字母映射成小写字母等。下面是通过查阅标准手册,记录的一些函数的用法,方便以后查找之用。

1,isalpha, 判断是否为字母
isdigit, 判断是否为数字
#include<ctype.h>
#include<stdio.h>
int main()
{
	int i=0;
	char str[]="c++11";
	while (str[i])
	{
		if (isalpha(str[i]))
			printf("character %c is alpha\n",str[i]);
		else if (isdigit(str[i]))
			printf("character %c is digit\n",str[i]);		
		else 
			printf("character %c is not alpha or digit\n",str[i]);
		i++;		
	}
}
输出结果为:

character c is alpha
character + is not alpha
character + is not alpha
character 1 is digit
character 1 is digit

isxdigit :判断是否为 A~F, a~f

2,isalnum: 是字母或者数字
#include<ctype.h>
#include<stdio.h>
int main()
{
	int i=0;
	int count=0;
	char str[]="c++11";
	//统计一个字符串中是字母或者数字的个数
	while (str[i])
	{
		if (isalnum(str[i])) 
			count++;
		i++;		
	}
	printf("there are %d alpha or digit is %s",count,str);
	return 0;
}
输出结果:
3


3,islower, 是否为小写,
isupper, 是否为大写
tolower, 转化为小写
touuper 转化为大写

#include<ctype.h>
#include<stdio.h>
int main()
{
	char str[]="I love ShangHai";
	//将字符串中的小写字母转化为大写字母
	int i=0;
	char c;
	while (str[i])
	{
		c=str[i];
		if (islower(c))str[i]=toupper(c);		
		i++;	
		
	}
	printf("%s\n",str);
	
}
I LOVE SHANGHAI


4, isspace: 判断一个字符是否为空格
#include <stdio.h>
#include <ctype.h>
int main ()
{
  char c;
  int i=0;
  char str[]="Example sentence to test isspace\n";
  while (str[i])
  {
    c=str[i];
    if (isspace(c)) c='\n';
    putchar (c);
    i++;
  }
  return 0;
输出为:
Example
sentence
to
test
isspace


一个应用:将一个包含0~9,A~F的字符串(十六进制)转化成整型:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

long atox(char *s)
{
	char xdigs[]="0123456789ABCDEF";
	long sum;
	while (isspace(*s))++s;
	
	for (sum=0L;isxdigit(*s);++s)
	{
		int digit=strchr(xdigs,toupper(*s))-xdigs; //地址相减
		sum=sum*16+digit;
	}
	return sum;
}

int main ()
{
	char *str="21";
	long l=atox(str);
	printf("%d\n",l);

	return 0;
}


函数strchr ,是包含中<string.h>中的一个函数,其原型为
const char * strchr ( const char * str, int character );
返回的是要查找的字符在字符串中第一次出现的位置,返回值是指向该字符的指针
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: