python3-实现atoi()函数

0.摘要

本文介绍c语言中的atoi函数功能,并使用python3实现。

1.atoi()函数

atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数。

函数定义形式:int atoi(const char *nptr);

函数会扫描参数 nptr字符串,跳过前面的空白字符(例如空格,tab缩进),直到遇上数字或正负符号才开始做转换;

在遇到非数字或字符串结束符('\0')结束转换,并将结果返回;

如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回 0 

2.python3代码

扫描二维码关注公众号,回复: 3824454 查看本文章

代码要解决三个主要问题:

  1. 字符串前有空白字符;
  2. ‘+’,‘-’ 处理问题;
  3. 浮点数问题;

首先,python的中的int()函数和float()函数功能可以说是非常强大,已经考虑了空白字符、正负号等问题

s0 = "123.456"
s1 = "+123.456    "
s2 = "    -123.456"
s3 = "    -123    "

print(float(s0))
print(float(s1))
print(int(float(s2)))
print(int(s3))

def my_atoi(num_string):
    if num_string == '':
        return 0
    else:
        try:
            f = float(num_string)
            i = int(f)
        except:
            return 0
        else:
            return i

if __name__ == '__main__':
    s0 = "123"
    s1 = "   -123.456    "
    s2 = "   +123.       "
    s3 = '  -123..456   '
    s4 = '  ++123.456   '
    s5 = '   0x123.45   '
    s6 = '    '

    print(my_atoi(s0))
    print(my_atoi(s1))
    print(my_atoi(s2))
    print(my_atoi(s3))
    print(my_atoi(s4))
    print(my_atoi(s5))
    print(my_atoi(s6))


猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/83269496