目录
strlen模拟实现(3种)
//计数器方式
int my_strlen(const char * str)
{
int count = 0;
while(*str)
{
count++;
str++;
}
return count;
}
//不能创建临时变量计数器
int my_strlen(const char * str)//递归
{
if(*str == '\0')
return 0;
else
return 1+my_strlen(str+1);
}
//指针-指针的方式
int my_strlen(char *s)
{
char *p = s;
while(*p != ‘\0’ )
p++;
return p-s;
}
strcpy模拟实现:
char *my_strcpy(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);assert(src != NULL);
while((*dest++ = *src++))
{
;
}
return ret;
}
strcat模拟实现:
char *my_strcat(char *dest, const char*src)
{
char *ret = dest;
assert(dest != NULL);
assert(src != NULL);
while(*dest)
{
dest++;
}
while((*dest++ = *src++))
{
;
}
return ret;
}
strcmp模拟实现:
int my_strcmp(const char* s1, const char* s2)
{
assert(s1 && s2);
while (*s1 == *s2)
{
if (*s1 == '\0')
return 0;
s1++;
s2++;
}return *s1 - *s2;
}
strstr模拟实现:
char* my_strstr(const char* dest, const char* src)
{
const char* s1 = dest;
const char* s2 = src;
const char* p = dest;
if (*s2 == '\0')
return dest;
while (*p != '\0')
{
s1 = p;
s2 = src;
while (*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
return p;
p++;
}
return NULL;
}
memcpy模拟实现:
void * memcpy ( void * dst, const void * src, size_t count)
{
void * ret = dst;
assert(dst);
assert(src);
/*
* copy from lower addresses to higher addresses
*/
while (count--) {
*(char *)dst = *(char *)src;
dst = (char *)dst + 1;
src = (char *)src + 1;
}
return(ret);
}
memmove模拟实现:(为辅助理解 下方有配图)
void* my_memmove(void* dest, void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
if (dest < src)//前向后
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else//后向前
{
while (num--)
{
*((char*)dest + num) = *((char*)src + num);}
}
return ret;
}