c语言code大集合

来源:互联网 发布:网络营销软件排行 编辑:程序博客网 时间:2024/06/15 22:59

//字符串转数字
#include<stdio.h>
#include<math.h>
int myAtoi(char* str)
{
if (str == NULL)
{
printf("字符串为空,输入无效");
return -1;
}


while (*str == ' ') //去掉起始空串
{
str++;
}
if (*str == '\0')
{
printf("字符串为空串");
return 0;
}
int sign = (*str == '-') ? -1 : 1;//确定符号位
if (*str == '+' || *str == '-')
{
str++;
}
int result = 0;
while (*str >= '0'&& *str <= '9')
{
result = result * 10 + (*str - '0');//*str - '0'指针差得到纯整数
str++;
}
return result*sign;
}


int main()
{
printf("%d\n", myAtoi("    12345"));
printf("%d\n", myAtoi("    +12345   "));
printf("%d\n", myAtoi("    -12345"));
printf("%d\n", myAtoi("    "));
printf("%d\n", myAtoi(""));
}
//output
12345
12345
- 12345
字符串为空串0
字符串为空串0

请按任意键继续. . .


//数字转字符串
#include<stdio.h>
#include<math.h>
char* myItoa(int num)
{
char str[1024];
int sign = num, i = 0, j = 0;
char temp[11];
if (sign < 0)
{
num = -num;
}
while (num>0)
{


temp[i] = num % 10 + '0';
num /= 10;
i++;

//while (num > 0);
//temp[i] = '\0';
i--;//back 最后一次自增
if (sign < 0)//加符号
str[j++] = '-';




while (i >= 0)
{
str[j++] = temp[i--];


}
str[j] = '\0';
return str;


}


int main()
{
printf("%s\n", myItoa(-123456));


printf("%s\n", myItoa(+123456));
return 0;
}

//output

-123456
123456
请按任意键继续. . .

0 0
原创粉丝点击