C语言 模拟实现strcpy 与 strlen
1、模拟实现strcpy
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *scopy(char *cop,const char *string) //模拟实现strcpy,将string中的内容复制到cop中
{
assert(string);
assert(cop);
char *copy = cop; //将cop字符串首地址存入copy中
while (*string)
{
*cop++ = *string++; //当*string元素为真时,把string中内容放到cop中,cop++,string++
}
*cop = '\0'; //字符串复制完毕,给cop结尾加上‘\0’
return copy; //返回复制的字符串
}
int main()
{
char arr1[]= "abcdef";
char arr2[120];
char* ret = scopy(arr2, arr1);
printf("%s", ret);
system("pause");
return 0;
}
运行结果如下图:
2、模拟实现 strlen
程序代码如下:
#include <stdio.h>
int slength(char *arr)
{
int count = 0;
while (*arr)
{
count++;
*arr++;
}
return count;
}
int main()
{
printf("%d", slength("abcdefrost"));
system("pause");
return 0;
}
运行结果如下: