【I】将给定的字符串转化为相应的整数
/*[1]. atoi 将给定的字符串转换为数字
* int m_atoi(char *strNum)
* @author arhaiyun
**/
bool g_bInvalidInput = false;
int m_atoi(char *strNum)
{
if(*strNum == '\0')
{
g_bInvalidInput = true;
return 0;
}
g_bInvalidInput = false;
//确定整数正负
int flag = 1;
if(*strNum == '+')
{
strNum++;
}
else if(*strNum == '-')
{
flag = -1;
strNum++;
}
int result = atoi_core(strNum, flag)
return result;
}
int atoi_core(char *strNum, int flag)
{
long long result = 0;
while(*strNum != '\0')
{
if(*strNum >= '0' && *strNum <= '9') //字符有效性
{
result = result * 10 + (*strNum - '0') * flag;
if(result > 0x7fffffff || result < 0x80000000) //整形范围限定
{
g_bInvalidInput = true;
resutl = 0;
break;
}
strNum++;
}
else
{
g_bInvalidInput = true;
result = 0;
break;
}
}
return (int)result;
}
【II】strcpy 字符串的复制从src到dst
/* [2].strcpy 字符串的复制从src到dst
* char* m_strcpy(char *dst, const char *src)
* @author arhaiyun
**/
char* m_strcpy(char *dst, const char *src)
{
assert(dst != NULL && src != NULL);
int srclen = strlen(src);
//考虑地址重叠问题
if(dst <= src || dst > src + srclen)
{
while((*dst++ = *src++) != '\0')
NULL;
}
else
{
for(int i = srclen; i >= 0; i--)
{
*(dst + i) = *(src + i);
}
}
return dst;
}
【III】strcat字符串连接
/* [3].strcat字符串连接
* char* m_strcat(char *dst, const char *src)
* @author arhaiyun
**/
char* m_strcat(char *dst, const char *src)
{
assert(dst != NULL && src != NULL);
char *pch = dst;
while(*pch != '\0')
{
pch++;
}
while(*src != '\0')
{
*pch++ = *src++;
}
*pch = '\0';
//dst = m_strcpy(dst + strlen(dst), src); 另外一种实现方式
return dst;
}