字符串转数字
例如" +123"->123;“123a4”->123;“abc123”->0
使用str[i]-'0’获取相对应的数字,num=num*10+数字 完成整体数字的转换
代码如下:
int Myatoi(const char* str)
{
assert(str != NULL);
if (str == NULL)
{
return 0;
}
while(*str == ' ')
{
str++;
}
int flg = 1;
int num = 0;
for (int i = 0; str[i] != '\0'; )
{
if (str[i] == '-')
{
flg = -1;
i++;
}
else if (*str == '+')
{
i++;
}
else if (isdigit(str[i]))
{
num = num * 10 + (str[i] - '0');
i++;
}
else
{
break;
}
}
return flg*num;//flg需要定义为全局变量
}
int main()
{
printf("%d\n",Myatoi("123"));
printf("%d\n",Myatoi("123a4"));
printf("%d\n",Myatoi("ab123"));
printf("%d\n",Myatoi(" 54ab"));
return 0;
}
数字转字符串
使用 数字+‘0’ 转为字符,
需要先获取各位数字到数组buf,最后逆置实现整体转化
void Myitoa(char* buf,int a)
{
int i = 0;
while (a!=0)
{
buf[i] = a % 10 + '0';
a /= 10;
i++;
}
buf[i] = '\0';
//--------逆序------
char temp;
i--;
for (int j = 0; j < i; j++,i--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
}
int main()
{
char* str = (char*)malloc(100 * sizeof(char));
Myitoa(str, 54321);
printf("%s\n", str);
free(str);
str = NULL;
return 0;
}
代码中逆序由数字反转实现
char temp;
i--;
for (int j = 0; j < i; j++,i--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
文章参考博文https://blog.csdn.net/cxchangzheng/article/details/96581124?