c语言重要库函数解读 和模拟实现————常用字符函数

常用字符函数总结

常用字符函数需要的头文件是`#include<ctype.h>

在这里插入图片描述
附上 ASCLLC码表
在这里插入图片描述

函数举例与实现

int isalnum(int ch)的使用和实现

该库函数功能为是否为字母或数字
在这里插入图片描述
经典案例 统计字符串中字母和数字的个数

#include<ctype.h>
#include<stdio.h>
#include<string.h>

int main()
{
    
    
	char ch[] = "abcd!1234";
	int sz = strlen(ch); //strlen 可以统计ch的长度
	int k = 0;
	for (int i = 0; i < sz; i++)
	{
    
    
		if (isalnum(ch[i]))  // 若ch[i]为字母或数字则为真 k++
		{
    
    
			k++;
		}
	}
	printf("%d", k);
	return 0  ;
}

实现:

#define _CRT_SECURE_NO_WARNINGS

#include<ctype.h>
#include<stdio.h>
#include<string.h>

int My_isalNum(int const x)
{
    
    
	if (('0' <= x)&&(x <= '9') || 
	('A' <= x) &&(x<= 'Z') || 
	('a' <= x)&&(x <= 'z'))
	{
    
    
		return 1;
	}
	else 
	{
    
    
		return 0;
	}
		
}
int main()
{
    
    
	int input = 0;
	scanf("%d", &input);
	int ret=My_isalNum(input);
	if (ret == 1)
	{
    
    
		printf("yes");
	}
	else
	{
    
    
		printf("no");
	}
	return 0;
}

int isxdigit(int ch)的使用和使用

该库函数功能为判断是否为十六进制数的字符

int main()
{
    
    
	int i = 48;
	 
	if (isxdigit(i))
	{
    
    
		printf("yes");
	}
	else
	{
    
    
		printf("no");
	}
	return 0;
}

实现: 实现方式与isalnum相同 只需要保证为1-9 a-e 大小写 即可。

大小写转换以及判定

大小写判定

int islower(int ch)的功能和实现
#include<ctype.h>
#include<stdio.h>
#include<string.h>

int main()
{
    
    
	int i = 48; //i属于[97,122] 为真 返回1

	if (islower(i))
	{
    
    
		printf("yes");
	}
	else
	{
    
    
		printf("no");
	}
	return 0;
}

实现 :

#include<ctype.h>
#include<stdio.h>
#include<string.h>

int My_islower(int x)
{
    
    

	if ((x >= 'a') && (x <= 'z'))
	{
    
    
		return 1;
	}
	else
	{
    
    
		return 0 ;
	}
}
int main()
{
    
    
	int i = 48; //i属于[97,122] 为真 返回1

	if (My_islower(i))
	{
    
    
		printf("yes");
	}
	else
	{
    
    
		printf("no");
	}
	return 0;
}

大小写转换

小写转换成大写: int toupper(int ch)

#include<ctype.h>
#include<stdio.h>
#include<string.h>


int main()
{
    
    
	int i = 112; // 小写字符p
	int ret= toupper(i);
	printf("%c", ret);
	return 0;
}

自我实现


#include<ctype.h>
#include<stdio.h>
#include<string.h>

int My__touPper(int x)
{
    
    
	if((x>='a')&&(x<='z'))
	{
    
    
		return  x - 32;
	}
	else
	{
    
    
		return 0;
	}
}


int main()
{
    
    
	int i = 112;
	int ret= My__touPper(i); // 是小写则返回大写 否则返回0
	printf("%c", ret);
	return 0;
}

注:

  1. 大写只需要变换条件即可。

猜你喜欢

转载自blog.csdn.net/qq_45849625/article/details/114760375