程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> C語言標准庫(1)—#include(ctype.h)

C語言標准庫(1)—#include(ctype.h)

編輯:關於C
C語言標准庫—#include 2014/11/25 by jxlijunhao 在這個頭文件中包含了對字符測試的函數,如檢查一個字符串中某一個字符是否為數字,或者字母等,還包含了字符映射函數,如將大寫字母映射成小寫字母等。下面是通過查閱標准手冊,記錄的一些函數的用法,方便以後查找之用。
1,isalpha, 判讀是否為字母 isdigit, 判讀是否為數字
#include
#include
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
#include
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
#include
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 
#include 
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 
#include 
#include 

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 ,是包含中中的一個函數,其原型為
const char * strchr ( const char * str, int character );
返回的是要查找的字符在字符串中第一次出現的位置,返回值是指向該字符的指針


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved