模拟实现atoi
- 主要思想:
将字符串转换成整数
1.如果字符串是空串,返回0
2.如果遇到数字字符和符号字符,将其转换,并往后找下一个,遇到其他字符就结束了
3.例如:“1A2” 则返回1 - 源代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int myAtoi(const char* str){
int flag = 1;
int ret = 0;
if (str == NULL){
return 0;
}
while(*str == ' '){
str++;
}
if (*str == '-'){
flag = -1;
str++;
}
while (*str >= '0' && *str <= '9'){
ret=ret*10+*str-'0';
str++;
}
return flag*ret;
}
int main()
{
const char str1[] = " 1e3lo";
const char str2[] = "123344";
const char str3[] = "A";
printf("str1=%s\n", str1);
printf("atoi(str1)=%d\n", atoi(str1));
printf("myAtoi(str1)=%d\n\n", myAtoi(str1));
printf("str2=%s\n", str2);
printf("atoi(str2)=%d\n", atoi(str2));
printf("myAtoi(str2)=%d\n\n", myAtoi(str2));
printf("str3=%s\n", str3);
printf("atoi(str3)=%d\n", atoi(str3));
printf("myAtoi(str3)=%d\n", myAtoi(str3));
system("pause");
return 0;
}
- 运行结果


