104.my_atoi函数的实现

【C语言】模拟实现atoi函数

可以把小写l转换为1,大写O转换为0

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define N 20

int my_atoidec(const char *str)
{
    int a=0;
    int sum=0;
    while(isdigit(*str)||*str=='l'||*str=='O')
    {
        a=*str;
        if(*str=='O')
        {
            a='0';
        }
        else if(*str=='l')
        {
            a='1';
        }
        else{}
        sum=sum*10+a-'0';// 减去字符0,也就是减去0的ASCII码值48,数字字符减去‘0’就得到了该数字
        str++;
    }
    return sum;
}
int my_atoihex(const char *str)
{
        int sum=0;
    while(isxdigit(*str))
    {
        int ch=0;
        if(isdigit(*str))
        {
            ch=*str-'0';
        }
        else
        {
            ch=tolower(*str)-'a'+10;
        }
        sum=sum*16+ch;
        str++;
    }
    return sum;
}
int my_atoioct(const char *str)
{
    int sum=0;
    while(isdigit(*str)&&*str!='8'&&*str!='9')
    {
        sum=sum*8+*str-'0';
        str++;
    }
    return sum;
}

int my_atoi(const char *str)
{
    int sum=0;
    assert(str!=nullptr);
    int tag=0;// 1负数,0正数
    while(isspace(*str))
    {
        str++;//跳过空白符
    }
    if(*str=='-')
    {
        tag=1;
        str++;
    }
    else if(*str=='+')
    {
        tag=0;
        str++;
    }
    if(*str=='0')
    {
        if(*(str+1)=='x'||*(str+1)=='X')
        {
            sum=my_atoihex(str+2);
        }
        else{
            sum=my_atoioct(str+1);
        }
    }
    else{
        sum=my_atoidec(str);
    }
    if(tag)
    {
        sum=-sum;
    }
    return sum;
}

int main()
{
    const char *str[]=
    {
        "12lO43",
        "12.43",
        "+12.45",
        "-12.45",
        "0123  425898",
        "0x123afbx",
        "-078",
        "qef2132",
    };
    int n=sizeof(str)/sizeof(str[0]);
    for(int i=0;i<n;++i)
    {
        printf("str[i]:%s==> %d\n",str[i],my_atoi(str[i]));
    }


	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值