1. 请实现一个itoa函数:
char* myitoa(int value, char* str, int radix)
{
const char chvalue[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char tmp;
unsigned int uvalue;
int index1 = 0, index2 = 0;
if (radix < 2 || radix > 36)
{
return NULL;
}
if (value < 0 && radix == 10)
{
uvalue = -value;
str[index1++] = '-';
}
else
{
uvalue = value;
}
do{
str[index1++] = chvalue[uvalue % radix];
uvalue /= radix;
} while (uvalue);
str[index1] = '\0';
index1--;
if (str[0] == '-') index2 = 1;
while (index2 < index1)
{
tmp = str[index2];
str[index2] = str[index1];
str[index1] = tmp;
index2++, index1--;
}
return str;
}
注意函数应该支持多种进制转换,不支持时返回值设置为NULL。
2. 请实现一个strcpy函数:
char *mystrcpy(char *dst, const char* src)
{
char* dststart = dst;
const char* srcend = NULL;
char *dstend = NULL;
size_t len = 0;
if (NULL == dst || NULL == src)
{
return NULL;
}
if (dst > src)
{
len = strlen(src);
srcend = src + len;
dstend = dst + len;
while (srcend != src - 1)
{
*dstend-- = *srcend--;
}
}
else
{
while ((*dst++ = *src++) != '\0');
}
return dststart;
}
注意,返回值为目标地址的起始地址,以便支持strlen(strcpy());这样的链式表达式;
在目标地址在源地址之后时,要从后往前拷贝字符串,以防目标地址和源字符串地址有重叠。
和此题相似的还有一题为实现一个高质量的memcpy函数,此时可以用一次拷贝一个int的办法以减少拷贝次数。
7492

被折叠的 条评论
为什么被折叠?



