zoukankan      html  css  js  c++  java
  • c语言实现atoi和itoa函数。

    首先看atoi函数:

    C语言库函数名: atoi
    功 能: 把字符串转换成整型数。
    名字来源:ASCII to integer 的缩写。
    原型: int atoi(const char *nptr);
    函数说明: 参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零,(意思是遇到非数字或结束符就停止)
    头文件: #include <stdlib.h>
    输入: -123ab;结果为-123;
    输入:abc,输出0.
    实现:
    int atoiOwn(const char *a)
    {
        int val=0;
        bool b_plus=true;//判断符号
        switch(*a) //过滤符号
        {
        case '+':
            a++;
            break;
        case '-':
            a++;
            b_plus=false;
            break;
        default:
            break;
        }
    
        while(*a>='0'&&*a<='9') //可以用isdigit判断。
        {
            val=val*10+(*a-'0');
            a++;
        }
        if(!b_plus)
            val=-val;
        return val;
    }
    int main()
    {
        
        char a[50];
        while(scanf("%s",a)!=EOF)
        {
            int ret=atoiOwn(a);
            printf("%d
    ",ret);
        }
    }
    char *itoa(int value, char *string, int radix);
    int value 被转换的整数,char *string 转换后储存的字符数组,int radix 转换进制数,如2,8,10,16 进制等
    char *  itoa ( int value, char * str, int base );
    Convert integer to string (non-standard function)
    Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

    If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other basevalueis always considered unsigned.

    str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
    This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

    A standard-compliant alternative for some cases may be sprintf:
    • sprintf(str,"%d",value) converts to decimal base.
    • sprintf(str,"%x",value) converts to hexadecimal base.
    • sprintf(str,"%o",value) converts to octal base.

    以下的代码只是模拟了部分功能: 

    #include<stdio.h>
    void itoa(int value, char *str)
    {
        if (value < 0) //如果是负数,则str[0]='-',并把value取反(变成正整数)
    
        {
            str[0] = '-';
            value = 0-value;
        } 
        int i,j;
        for(i=1; value > 0; i++,value/=10) //从value[1]开始存放value的数字字符,不过是逆序,等下再反序过来
    
            str[i] = value%10+'0'; //将数字加上0的ASCII值(即'0')就得到该数字的ASCII值
    
        for(j=i-1,i=1; j-i>=1; j--,i++) //将数字字符反序存放
    
        {
            str[i] = str[i]^str[j];
            str[j] = str[i]^str[j];
            str[i] = str[i]^str[j];
        }
        if(str[0] != '-') //如果不是负数,则需要把数字字符下标左移一位,即减1
    
        {
            for(i=0; str[i+1]!=''; i++)
                str[i] = str[i+1];
            str[i] = '';
        }
    }
    
    void main()
    {
        int value = -1212345;
        char str[10] = {''}; //记得把str全填充为'' 这个错误,其实这样赋值只是把第
          1个元素赋值为,后面的都默认用填充,如果是char str[10]={'1'};
    只有第一个为‘1’,后面都是.但千万不要以为写成char str[10];不赋值也可以。这样写里面的内容是乱的。
    itoa(value, str); printf(
    "The result is:%s ", str); }

    另一种写法:

    void intToStr(int num,char str[])
    {
        int i=0,j=0,isNeg=0;
        if(num<0)
        {
            num*=-1;
            isNeg=1;
        }
        do{
            str[i++]=(num%10)+'0';
            num/=10;
        }while(num);
    
        if(isNeg)
            str[i++]='-';
    
        //reverse the characher;
        for(int m=0,n=i-1;m<n;m++,n--)
            swap(str[m],str[n]);
    
        str[i]='';
    }

    为什么写成:

    do{
            str[i++]=(num%10)+'0';
            num/=10;
        }while(num);
    而不是
    while(num)
    {
      

    }
    因为当输入为0时,while(num)一次都不会执行,导致最后输出的是空串。因为至少要执行一次,所以用do while.

    更好的办法:

    http://blog.csdn.net/solstice/article/details/5139302

    http://stackoverflow.com/questions/3440726/what-is-the-proper-way-of-implementing-a-good-itoa-function

    参考;http://www.cppblog.com/lizhongxu2008/archive/2009/02/11/73470.html

     许多实现:http://www.jb.man.ac.uk/~slowe/cpp/itoa.html#dev

        
    /**
        
     * Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C":
        
     */
        
    void strreverse(char* begin, char* end) {
        
        char aux;
        
        while(end>begin)
        
            aux=*end, *end--=*begin, *begin++=aux;
        
    }
        
    void itoa(int value, char* str, int base) {
        
        static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
        
        char* wstr=str;
        
        int sign;
        
    
        
        // Validate base
        
        if (base<2 || base>35){ *wstr=''; return; }
        
    
        
        // Take care of sign
        
        if ((sign=value) < 0) value = -value;
        
    
        
        // Conversion. Number is reversed.
        
        do *wstr++ = num[value%base]; while(value/=base);
        
        if(sign<0) *wstr++='-';
        
        *wstr='';
        
    
        
        // Reverse string
        
        strreverse(str,wstr-1);
        
    }
        
        
        
    /**
        
     * Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C"
        
     * with slight modification to optimize for specific architecture:
        
     */
        
    void strreverse(char* begin, char* end) {
        
        char aux;
        
        while(end>begin)
        
            aux=*end, *end--=*begin, *begin++=aux;
        
    }
        
    void itoa(int value, char* str, int base) {
        
        static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
        
        char* wstr=str;
        
        int sign;
        
        div_t res;
        
    
        
        // Validate base
        
        if (base<2 || base>35){ *wstr=''; return; }
        
        
        // Take care of sign
        
        if ((sign=value) < 0) value = -value;
        
    
        
        // Conversion. Number is reversed.
        
        do {
        
            res = div(value,base);
        
            *wstr++ = num[res.rem];
        
        }while(value=res.quot);
        
        if(sign<0) *wstr++='-';
        
        *wstr='';
        
    
        
        // Reverse string
        
        strreverse(str,wstr-1);
        
    }
  • 相关阅读:
    黑苹果崩溃恢复
    黑苹果声音小解决方法
    idea plugin 进度条
    phpstorm 插件
    awesome mac
    webstorm vue eslint 自动修正配置
    Laravel/php 一些调试技巧
    php ZipArchive 压缩整个文件夹
    laravel 模型事件 updated 触发条件
    php 开启 opcache 之后 require、include 还会每次都重新加载文件吗?
  • 原文地址:https://www.cnblogs.com/youxin/p/3235802.html
Copyright © 2011-2022 走看看