不使用c的任何庫函數 實現字符串到整數的轉換 整數到字符串的轉換

轉載請標明出處:http://www.cnblogs.com/NongSi-Net/p/6805844.htmlhtml

今天主要總結下:完成編程:編程

一、除printf函數以外,不用任何c語言庫函數,實現將字符串轉化爲整數的函數myatoi(能夠支持負整數的轉化)。函數

二、除printf函數以外,不用任何c語言庫函數,實現將整數轉化爲字符串的函數myitoa(能夠支持負整數的轉化)。spa

若是想理解這個問題,必須知道一個知識:code

字符‘0’+一個整數,則獲得這個整數的字符型。反之,字符型-字符‘0’則獲得整數值。htm

如:‘0’+9=‘9’;blog

      ‘9’-‘0’=9;ip

代碼以下:字符串

/*
 ============================================================================
 Name        : mystoi.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>

void mylength(int a,int *lenth)
{
    int i = 0;
    if(lenth == NULL)
    {
        printf("mylength fun error\n");
    }
    do
    {
        a = a / 10;
        i++;
    }while(a);
    *lenth = i;
}

void reserve(int lenth,char buf[])
{
    int i = 0;
    char temp;
    for(i = 0;i<lenth/2;i++)
    {
        temp = buf[i];
        buf[i] = buf[lenth-i-1];
        buf[lenth-i-1] = temp;
    }
}
//1.除printf函數以外,不用任何c語言庫函數,實現將整數轉化爲字符串的函數myitoa(能夠支持負整數的轉化)。
void myitoa(int a,char buf[])
{
    int i = 0;
    int sign;
    int length = 0;
    mylength(a,&length);
    if((sign = a) < 0)
        a = -a;
    for(i = 0;i<length;i++)
    {
        buf[i] = '0' + a % 10;
        a = a / 10;
    }
    if(sign < 0)
    {
       buf[i++] = '-';
       reserve(length+1,buf);
    }else
    {
        reserve(length,buf);
    }
}

void slength(char buf[],int *length)
{
    int i = 0;
    while(buf[i])
    {
        i++;
    };
    *length = i;
}
//二、除printf函數以外,不用任何c語言庫函數,
//實現將字符串轉化爲整數的函數myatoi(能夠支持負整數的轉化)。
int myatoi(char buf[])
{
    int sum = 0;
    int i = 0;
    int flag = 1;
    while(buf[i])
    {
        if(buf[i] == ' ')
            i++;
        else if(buf[i] == '+')
        {
            i++;
            flag = 1;
        }
        else if(buf[i] == '-')
        {
            i++;
            flag = -1;
        }
        else if(buf[i]>='0'&&buf[i]<='9')
        {
            sum = sum*10+(buf[i] - '0');
            i++;
        }
        else
            return 0;
    }
    sum = sum * flag;
    return sum;
}

int main(void) {
    int abc = 123456789;
    char arr[1024] = "--+1836";
    int length = 0;
    char buf[1024] = {0};
    printf("the following thing is myitoa...Int---->string\n\n");
    myitoa(abc,buf);
    printf("the string is %s.\n\n",buf);
    printf("the following thing is myatoi...string---->Int\n\n");
    slength(arr,&length);
    printf("the string's length is %d.\n\n",length);
    printf("the Intger is %d.\n\n",myatoi(arr));
    return 0;
}
相關文章
相關標籤/搜索