1、itoa函數實現
#includevoid itoa(int i, char *string) { int power=0,j=0; j=i; for( power=1;j>10;j/=10) power*=10; for(;power>0;power/=10) { *string++='0'+i/power; i%=power; } *string='\0'; printf("%s\n",string); } void main() { char string[20]; itoa(12345, string); printf("%s\n",string); }
其中power相當於類似於1234,其power=1000;134,其power=100
*string++='0'+i/power;//獲得取得字符的asicii碼
i/power取得字符,例如1234/1000=1;234/100=2
2、atoi實現
int atoi(char *str)
{
if(!str)
return -1;
bool bMinus=false;
int result=0;
if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))
{
if(*str=='-')
bMinus=true;
*str++;
}
while( *str != '\0')
{
if('0'> *str || *str>'9')
break;
else
result = result*10+(*str++ - '0');
}
if (*str != '\0')//no-normal end
return -2;
return bMinus?-result:result;
}
if(('0'>*str || *str>'9')&&(*str=='+'||*str=='-'))//判讀第一個字符是否為數字的正負號
if (*str != '\0')//no-normal end,當上文的while循環不正常退出,應視為字符串不合法,例如“+1234abc”
測試:
char *c1 = "12345";
char *c2 = "-12345";
char *c3 = "bat-123";
char *c4 = "+123abc";
printf("c1=%d\n",atoi(c1));
printf("c2=%d\n",atoi(c2));
printf("c3=%d\n",atoi(c3));
printf("c4=%d\n",atoi(c4));
c1=12345
c2=-12345
c3=-2
c4=-2