您的位置:首页 > 编程语言 > C语言/C++

C语言,模拟实现strcpy、strlen函数

2016-10-16 16:05 411 查看

模拟实现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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: