模拟实现C语言常用函数(1)
1.模拟strcpy
#include <stdio.h>
#include <assert.h>
char * my_strcpy(char* dest, const char* src)
{
char* ret = dest;
assert(dest);
assert(src);
while (*dest++ = *src++) {
;
}
return ret;
}
int main()
{
char arr[] = "abcdefg";
char arr1[20] = {0};
my_strcpy(arr1, arr);
printf("%s\n", arr1);
return 0;
}
![image-20240627165259120](https://img-blog.csdnimg.cn/img_convert/c21adc958668f9b560e283c50bdcaed7.png)
2.模拟strlen
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
if (*str != '\0'){
return 1 + my_strlen(str + 1);
}else{
return 0;
}
}
int main()
{
char arr[] = "abcdefg";
size_t len=my_strlen(arr);
printf("strlen=%zd\n", len);
return 0;
}
![image-20240627165922133](https://img-blog.csdnimg.cn/img_convert/f45140e813d7afe638904f90e74eeff1.png)
3.模拟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 str[20] = "hello ";
const char * p = "world";
printf("%s\n",my_strcat(str,p));
return 0;
}
![image-20240627170537089](https://img-blog.csdnimg.cn/img_convert/83deab08880907132686f52150a01695.png)