1. 程式人生 > >自定義數字和字串的轉換函式

自定義數字和字串的轉換函式

C語言中,常見的字串與數字之間的相互轉換的庫函式有:atof(字串轉換成浮點數)、atoi(字串轉換成整型數)、atol(字串轉換成長整形數)、itoa(整型數轉換成字串)、ltoa(長整型數轉換成字串)等。在求職中,讓求職者自定義此類函式的實現是為了考察求職者對基本功的掌握。
下面給出兩個示例:

#include<stdio.h>

int Myatoi(char *str)
{
      if(str==NULL)
      {
            printf("invalid input");
            return -1;
      }
      while
(*str=='') { str++; } while((*str==(char)0xA1)&&(*(str+1)==(char)0xA1))//0xA1是漢字開始的編碼 { str+=2; } int nSign=(*str=='-')?-1:1; if(*str=='+'||*str=='-') { str++; } int nResult=0; while(*str>='0'&&*str
<='9') { nResult=nResult*10+(*str-'0'); str++; } return nResult*nSign; } int main() { printf("%d\n",Myatoi("12345"); return 0; } //程式輸出結果 //12345
#include<stdio.h>

char* Myitoa(int num)
{
      char str[1024];
      int sign=num,i=0,j=0;
      char
temp[11]; if(sign<0) { num=-num; }; do { temp[i]=num%10+'0'; num/=10; i++; }while(num>0); if(sign<0) { temp[i++]='-'; } temp[i]='\0'; i--; while(i>=0) { str[j]=temp[i]; j++; i--; } str[j]='\0'; return str; } int main() { printf("%d\n",Myitoa(-12345)); return 0; } //程式輸出結果: //-12345