atoi函數和itoa函數C代碼實現

一、atoi函數實現

     1、atoi (表示 ascii to integer)是把字符串轉換成整型數的一個函數。

     2、C代碼實現如下

 

#include <stdio.h>
#include <ctype.h>

/*atoi() function:convert string to integer*/
int atoi(char str[])
{
    int i = 0;
    int sign = 0;/*record the sign*/
    int n = 0;/*record the integer*/
    
    while(isspace(str[i]))i++; /*skip white space*/
    
    sign = (str[i] == '-')?-1:1;
    
    if((str[i] == '+') ||(str[i] == '-'))i++; /*skip sign*/
    
    while(isdigit(str[i]))
    {
        n = n*10 + (str[i] -'0');
        i++;
    }
 
    return n*sign;  /*return the integer value*/
}


int main(void) {
    
    char s[] = "-123";
    
    int n = 0;
    n = atoi(s);
    
    printf("integer = %d",n);
    
    return 0;
}

二、itoa函數實現

1、itoa函數通過把整數的各位上的數字加“0”轉換成char類型並存到字符數組中。但是要注意,需要採用字符串倒置reverse函數處理下。

2、C代碼實現如下

#include <stdio.h>
#include <string.h>

/*reverse函數:倒置字符串S中各個字符的位置 */
 void reverse(char s[])
 {
     int tmp = 0;
     
     for(int i = 0,j = strlen(s)-1; i < j; i++, j--)
     {
         tmp  = s[i];
         s[i] = s[j];
         s[j] = tmp;
     }
 }
 
 
 /*itoa函數,將數字轉換爲字符串並保存在S中 */
 void itoa(int n,char s[])
 {
    int i = 0;
    int sign = 0;

    if((sign = n) < 0)  //記錄符號 
        n = -n;  //使n成爲正數 
 
     do
     {
         s[i++] = n%10 + '0'; //取下一個數字 
         
     }while((n /= 10) > 0); //刪除當前位上的數值 
     
     if(sign < 0)
        s[i++] = '-';
    
    s[i] = '\0';
    
    reverse(s);
 }
 

int main(void) {
    int n; 
    char s[20]; //save the string 
    n = -123;   // test input integer
    
    itoa(n,s);  //convert function
      
    printf("%s",s); //print the string 
    
    return 0;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章