C语言:将字符串转成数字,例如"1234"->1234 int Myatoi(const char *str); 将数字转成字符串,例如1234->"1234" void Myitoa(char *s

从字符串中获取数字和将数字转成字符串

#include<stdio.h>

int Myatoi(const char* str);//字符串转数字
void Myitoa(char *str, int n);//数字转字符串
int main()
{
	char str1[30] = "HELLO";
	Myitoa(str1, 1234);
	printf("%s\n", str1);
	Myitoa(str1, -1234);
	printf("%s\n", str1);
	Myitoa(str1, 0);
	printf("%s\n", str1);
	//Myatoi字符串转数字
	printf("%d\n", Myatoi("Hello"));
	printf("%d\n", Myatoi("Hello0"));
	printf("%d\n", Myatoi("He- 1 0 0llo"));
	printf("%d\n", Myatoi("1234"));
	printf("%d\n", Myatoi("-1    2   3   4"));
	getchar();
	return 0;
}
int Myatoi(const char* str)
{
	const char *p = NULL;
	p = str;
	int len = 0;
	int sign = 1;
	int n = 0;
	int bit = 0;
	int i = 0;//字符串的指针
	while (*p != '\0')
	{
		len++;
		p++;
	}//判断字符串的长度可以使用strlen()
	for (i=0; i < len; i++)
	{
		if (*(str + i) <= '9' && *(str + i)>'0')//寻找第一个非零的数字
		{
			n = *(str + i) - '0';
			break;
		}
		if (len == i + 1)
			return 0;//没有找到一个满足的数字
		
	}
	for (int j = i-1; j >= 0; j--)
	{
		if (*(str + j) == ' ')//空格可以跳过
			continue;//比如   -   123
		else if (*(str + j) == '-')
		{
			sign = -1;//判断出来是负数
			break;
		}
		else
			break;
	}
	//上面得到第一个数字str[i]和符号sign,还有第一个数字的指针i
	for (int k = i + 1; k < len; k++)
	{
		if (*(str + k) <= '9' && *(str + k)>'0')
			n = n * 10 + *(str + i) - '0';
		else if (*(str + k) ==' ')
			continue;
		else
			break;
	}
	return sign *n;
}
void Myitoa(char *str, int n)
{
	//函数将一个整形的 数字写入字符串  1234->"1234"   -123->"-123"
	//选择从字符串的尾部开始写
	int bit = 0;
	char ch;
	while (*str != '\0')
		str++;
	if (n < 0)
	{
		*str = '-';
		str++;
		n = -n;
	}
	//现在的指针还有没有写入  此时*str=NULL
	do
	{
		*(str + bit) = n % 10 + '0';//最低位
		n /= 10;
		bit++;
	} while (n);
	//现在的字符站串已经写入了   但是  1234-‘4321’
	for(int i = 0; i < bit / 2; i++ )
	{
		ch = *(str + i);
		*(str + i) = *(str + bit - 1 - i);
		*(str + bit - 1 - i)=ch;
	}
	*(str+bit) = '\0';
}

猜你喜欢

转载自blog.csdn.net/qq_40757240/article/details/88073415