分类: C/C++
2011-10-07 16:45:19
strcpy函数重写
char *Strcpy(char *Des, const char *Src)
{
assert((Des != NULL) && (Src != NULL));
char *Address = Des;
while ((*Des++ = *Src++) != '\0')
;
return Address;
}
strncpy函数重写
char *Strncpy(char *Des, const char *Src, size_t size)
{
assert((Des != NULL) && (Src != NULL));
char *Address = Des;
while (size-- > 0 && (*Des++ = *Src++) != '\0')
{
;
}
if (*(Des - 1) != '\0')
{
*Des = '\0';
}
return Address;
}
strlen函数重写
unsigned int Strlen(const char *Src)
{
assert(Src != NULL);
unsigned int len = 0;
while (*Src++ != '\0')
{
len++;
}
return len;
}
strcat函数重写
char *Strcat(char *FirStr, const char *SecStr)
{
assert(FirStr != NULL && SecStr != NULL);
char *Address = FirStr;
while (*FirStr++ != '\0')
;
FirStr--;
while ((*FirStr++ = *SecStr++) != '\0')
;
return Address;
}
strcmp函数重写
int Strcmp(const char *str1, const char *str2)
{
assert(str1 != NULL && str2 != NULL);
while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2)
{
str1++;
str2++;
}
int res = *str1 - *str2;
if (res == 0)
return 0;
else if (res > 0)
return 1;
else
return -1;
}
strncmp函数重写
int Strncmp(const char *str1, const char *str2, size_t size)
{
assert(str1 != NULL && str2 != NULL);
while (size > 0 && *str1 != '\0' && *str2 != '\0' && *str1 == *str2)
{
size--;
str1++;
str2++;
}
if (size > 0)
{
int res = *str1 - *str2;
if (res == 0)
{
return 0;
}
else if (res > 0)
return 1;
else
return -1;
}
else
{
return 0;
}
}
memcpy函数重写
void *Memcpy(void *Des, const void *Src, size_t count)
{
assert(Des != NULL && Src != NULL);
void *Address = Des;
char *DesCh = (char *)Des;
char *SrcCh = (char *)Src;
assert(DesCh > SrcCh + count || SrcCh > DesCh + count);
while (count-- > 0)
{
*DesCh++ = *SrcCh++;
}
return Address;
}
memmove函数重写
void* Memmove(void *Des, const void *Src, size_t count)
{
assert(Des != NULL && Src != NULL);
void *Address = Des;
if (Des <= Src || (char *)Des >= (char *)Src + count)
{
while (count-- > 0)
{
*(char *)Des = *(char *)Src;
Des = (char *)Des + 1;
Src = (char *)Src + 1;
}
}
else
{
Des = (char *)Des + count - 1;
Src = (char *)Src + count - 1;
while (count-- > 0)
{
*(char *)Des = *(char *)Src;
Des = (char *)Des - 1;
Src = (char *)Src - 1;
}
}
return Address;
}
memset函数重写
void *Memset(void *Src, int ch, unsigned int count)
{
assert(Src != NULL);
void *Address = Src;
while (count-- > 0)
{
*(char *)Src = ch;
Src = (char *)Src + 1;
}
return Address;
}
strstr函数重写
char *Strstr(char *str1, char *str2)
{
assert(str1 != NULL && str2 != NULL);
for (int i = 0; i < strlen(str1) - strlen(str2) + 1; i++)
{
int j = 0;
if (str1[i] == str2[j])
{
int k = i;
for (++k, ++j; k < strlen(str1) && j < strlen(str2); k++, j++)
{
if (str1[k] != str2[j])
{
break;
}
}
if (j >= strlen(str2))
{
return str1+i;
}
}
}
return NULL;
}