1.strlen->my_strlen
#include<stdio.h>
#include<assert.h>
size_t my_strlen(const char* str)
{
size_t count = 0;
assert(str);
while (*str != '\0')
{
*str++;
count++;
}
return count;
}
int main()
{
char arr[] = "abcde";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
2.strcpy->my_strcpy
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(dest && src);
char ret = dest;
while (*src)
{
*dest++ = *src++;
}
*dest = *src;
return ret;
}
int main()
{
char arr1[] = "abcd";
char arr2[10] = { 0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
3.strcat->my_strcat
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* dest, const char* src)
{
char* ret = dest;
assert(dest && src);
while (*dest != '\0')
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[10] = "hello";
my_strcat(arr1, "bit");
printf("%s\n", arr1);
return 0;
}
4.strstr->my_strstr
#include<stdio.h>
#include<assert.h>
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* p = str1;
while (*p)
{
s1 = p;
s2 = str2;
while (s1 != '\0' && s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)p;
}
p++;
}
return NULL;
}
int main()
{
char arr1[] = "abcdefg";
char arr2[] = "cde";
char* ret = my_strstr(arr1, arr2);
if (ret == NULL)
{
printf("字串不存在\n");
}
else
{
printf("%s\n", ret);
}
return 0;
}
5.memcpy->my_memcpy
#include<stdio.h>
#include<string.h>
#include<assert.h>
void* my_memcpy(void* dest,const void* src, size_t num)
{
assert (dest && src);
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
my_memcpy(arr2, arr1, 40);
int i = 0;
for (i = 0; i < 8; i++)
{
printf("%d ", arr2[i]);
}
return 0;
}
6.memmove->my_memmove
#include<stdio.h>
#include<assert.h>
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;
}
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr1 + 2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr1[i]);
}
return 0;
}
7.strcmp->my_strcmp
#include<stdio.h>
#include<assert.h>
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
if (*str1 > *str2)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
char arr1[20] = "abcde";
char arr2[] = "abcd";
int ret = my_strcmp(arr1, arr2);
if (ret < 0)
{
printf("<\n");
}
else if (ret == 0)
{
printf("==\n");
}
else
{
printf(">\n");
}
return 0;
}