本篇文章为一些字符串函数的模拟实现,对于字符串函数的深入了解可以浏览C语言——字符函数和字符串函数_学习笔记
size_t my_strlen(const char* ptr)
{
assert(ptr);
char* start = ptr;
while (*ptr != '\0')
{
ptr++;
}
return (size_t)(ptr - start);
}
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);
char* ptr = dest;
while (*dest++ = *src++)
{
;
}
return ptr;
}
char* my_strcat(char* dest, const char* src)
{
assert(dest && src);
char* ptr = dest;
while (*dest != '\0')
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ptr;
}
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
return *str1 - *str2;
}
const char* my_strstr(const char* s1, const char* s2)
{
assert(s1 && s2);
char* cp = s1;
char* p1 = NULL;
char* p2 = NULL;
if (*s2 == '\0')
{
return s1;
}
while (*cp)
{
p1 = cp;
char* p2 = s2;
while (*p1 == *p2 && *p1 && *p2)
{
p1++;
p2++;
}
if (*p2 == '\0')
{
return cp;
}
cp++;
}
return NULL;
}
char* my_strncpy(char* s1, const char* s2, size_t num)
{
assert(s2);
char* ret = s1;
while (*s2 && num)
{
*s1 = *s2;
num--;
s1++;
s2++;
}
return ret;
}
char* my_strncat( char* s1, const char* s2,size_t num)
{
assert(s2);
char* ret = s1;
while (*s1)
{
s1++;
}
while (*s2 && num)
{
*s1 = *s2;
s1++;
s2++;
num--;
}
return ret;
}
int my_strncmp(const char *s1, const char *s2, size_t n)
{
while(n--)
{
if(*s1 != *s2)
return *s1 - *s2;
else if(*s1 == '\0')
return 0;
s1++;
s2++;
}
return 0;
}