【ARM 嵌入式 C 字符串系列 23.7 -- C 实现函数 isdigit 和 isxdigit】


请阅读【嵌入式开发学习必备专栏 】


isdigit 和 isxdigit C代码实现

在C语言中,isdigitisxdigit函数用于检查一个字符是否分别为十进制数字或十六进制数字。以下是这两个函数的简单实现,它们依靠标准ASCII码值来判断字符。

实现 isdigit

#include <stdbool.h> // 为了使用bool类型

// 检查字符c是否为十进制数字
bool isdigit(int c) 
{
    return c >= '0' && c <= '9';
}

这个isdigit函数接受一个int类型的参数(尽管它实际上应该是一个字符),并检查这个字符是否在'0''9'的范围内。如果是,函数返回true;否则返回false

实现 isxdigit

#include <stdbool.h> // 为了使用bool类型

// 检查字符c是否为十六进制数字
bool isxdigit(int c) 
{
    return (c >= '0' && c <= '9') || 
           (c >= 'a' && c <= 'f') || 
           (c >= 'A' && c <= 'F');
}

这个isxdigit函数同样接受一个int类型的参数,并检查这个字符是否为有效的十六进制数字。有效的十六进制数字包括'0''9''a''f'以及'A''F'。如果字符是其中之一,函数返回true;否则返回false

使用示例

#include <stdio.h>

int main(void) 
{
    char ch;
    ch = '5';
    if (isdigit(ch))
        printf("%c is a decimal digit.\n", ch);
    else
        printf("%c is not a decimal digit.\n", ch);
    ch = 'X';
    if (isxdigit(ch))
        printf("%c is a hexadecimal digit.\n", ch);
    else
        printf("%c is not a hexadecimal digit.\n", ch);
    ch = 'g'; // 注意:小写'g'不是十六进制数字
    if (isxdigit(ch))
        printf("%c is a hexadecimal digit.\n", ch);
    else
        printf("%c is not a hexadecimal digit.\n", ch);
    return 0;
}

这个示例程序展示了如何使用isdigitisxdigit函数。请注意,尽管我们在这里提供了简单的实现,标准C库中已经提供了这些函数的实现,通常在<ctype.h>头文件中。在实际的应用程序中,建议直接使用标准库的函数,以保证最大的兼容性和性能。

  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

主公CodingCos

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值