#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <vld.h>
//字符转数字("123"->123,"12a3"->12,"a12"->0) 遇到字母就退出
int Myatoi(const char *str)
{
assert(str!=NULL);
if(str==NULL)
{
return 0;
}
int sum = 0;
while(isdigit(*str))
{
sum = sum*10 + *str - '0';
str++;
}
return sum;
}
//数字转字符 123-》“123”
void StrReverse(char *str)
{
char *p = str;
char tmp;
while(*p!='\0')
{
p++;
}
p--;
for(;str<=p;str++,p--)
{
tmp = *str;
*str = *p;
*p = tmp;
}
}
int GetFigure(int num)
{
int count=0;
while(num!=0)
{
count++;
num /= 10;
}
return count;
}
char *Myitoa(int num)
{
char *p=(char*)malloc(GetFigure(num)+1 * sizeof(char));
int i=0,j=0;
while(num!=0)
{
p[i++] = num%10 + '0';
num /= 10;
}
p[i]='\0';
StrReverse(p);
return p;
}
int main()
{
printf("%d\n",Myatoi("a12"));
printf("%d\n",Myatoi("123"));
printf("%d\n",Myatoi("12a3"));
char str5[20];
printf("%s\n",Myitoa(123456789));
char *str = Myitoa(123456789);
printf("%s\n",str);
free(str);
return 0;
}
打印结果:
0
123
12
123456789
123456789