重写strncpy()函数
char* repeat_strncpy(char* s, int n)
{
int len = strlen(s); // 目标:拷贝s的n个字符出去
// 但是len可能比n小
// 此时,需要把n重新赋值为len
int copyCount = len < n ? len : n;
char* ptr = s;
char* p = new char[copyCount+1];
// ver3 by wdz
while (ptr - s < copyCount) // 利用指针偏移量进行循环;
{
*p++ = *ptr++;
}
*p = '\0';
return p - copyCount; // 注意指针偏移到数组末端,需要返回到起始位置再return;
}
重写strcmp()函数,并返回目标字符串首地址
//若“at”在“hats”内,则返回"hats"中a的地址;
const char* string_in(const char* s1, const char* s2)
{
if (!s1 || !s2)
return NULL;
const char* n = s1; // 下一个查找位置
while (*n)
{
// 先找到第一个相等的
const char* f = n;
while (*f != *s2 && *f != '\0')
{
++f;
}
if (*f == '\0')
{
// 到了结尾也没找到啊!
return NULL;
}
else
{
// 可能就要找到了
// 先确定下一次查找的起始位置
n = f + 1;
// 继续进行本次查找比较
// 看看能否完成全部匹配
const char* q = s2;
while (*q)
{
if (*f != *q)
{
// a!失败了
// 继续查找下一个吧
break;
}
++f;
++q;
}
if (!*q)
{
// 找到了!
return n - 1;
}
}
}
}
重写strchr()函数
char* repeat_strchr(char* s, int c)
{
char* ptr = s;
while (*ptr != '\0')
{
if (c == *ptr )
{
return ptr;
}
++ptr;
}
return NULL;
}
重写atoi()函数
int repeat_atoi(char* s)
{
char* ptr = s;
int i = 0, n = 0, sign = 1;
for (i = 0; isspace(ptr[i]); i++) //跳过空白符;
;
if (ptr[i] == '+' || ptr[i] == '-') //跳过符号
{
sign = (ptr[i] == '-') ? -1 : 1;
i++;
}
for (n = 0; isdigit(ptr[i]); i++)
n = 10 * n + (ptr[i] - '0'); //将数字字符转换成整形数字
return sign * n;
}