C语言实现字符串与数字互转(逆序)

字符串转数字

例如" +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?

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值