模拟实现strcpy、strlen函数
1、模拟实现strcpy
方法一:
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[10] = {0};
char arr2[] = "abcdef";
strcpy(arr1, arr2);//arr1目标,arr1和arr2位置不能改变
printf("%s\n",arr1);
return 0;
}
方法二:
#include<stdio.h>
#include<assert.h>
char *my_strcpy(char *dest,const char *src)//dest= Destination,src=source
{
char *ret = dest;
assert(dest);//assert确保你的程序按目标正常运行
assert(src);
while(*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char *p = "hello";
char arr[10];
printf("%s\n",strcpy(arr,p));
return 0;
}
2.模拟实现strlen
#include<stdio.h>
#include<assert.h>
int my_strlen(const char *str)
{
int count = 0;
assert(str);
while(*str)
{
count++;
str++;
}
return count;
}
int main()
{
printf("%d\n",my_strlen("hello world"));
return 0;
}