很多时候, 会将数据压缩存储, 这时候需要把数字存储到字符串当中
而分割后还原的atoi有个问题, 国内我发现都只是简单的告诉你这是字符串转数字的函数.....
还是老外说的明白:
int atoi( char* pStr )
write the definition for this function without using any built-in functions. if pStr is null, return 0. if pStr contains non-numeric characters, either return 0 (ok) or return the number derived so far (better) (e.g. if its “123A”, then return 123). assume all numbers are positive. plus or minus signs can be considered non-numeric characters. in order to solve this program, the programmer must understand the difference between the integer 0 and the character ‘0’, and how converting ‘0’ to an int, will not result in 0. in other words, they have to understand what ascii is all about.
意思是返回值根据不同情况都得出同一个值
.字符串为null 返回0
.字符串不是数字 返回0
.字符串是0 也返回0
所以如果你用到这个方法, 而且需要处理的话, 尽量避免0和字母混合的情况出现
实现结构很简单
int atoi( char* pStr )
{
int iRetVal = 0;
int iTens = 1;
if ( pStr )
{
char* pCur = pStr;
while (*pCur)
pCur++;
pCur--;
while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' )
{
iRetVal += ((*pCur - '0') * iTens);
pCur--;
iTens *= 10;
}
}
return iRetVal;
}
出处:
http://www.techinterview.org/post/526339864/int-atoi-char-pstr/