//第一题,实现字符串的复制
//笔试题常考啊这个东西//
//函数原型为: char *strcpy(char *dst,const char *src)
//需要注意的点有:1、形参中的const
//2、assert在assert.h中
//3、while语句中判断条件
//4、*dst = '\0';
//5、测试时候,元字符串定义为char *src,而目的字符串定义为 char dst[100],
//因为char *src定义的是不可变的字符串。否则会出现内存错误的哈~
#include <stdio.h>
#include <assert.h>
char *strcpy(char *dst,const char *src){
assert(*dst != NULL && *src != NULL);
char *temp = dst;
while(*src !='\0'){
*dst++= *src++;
}
*dst ='\0'; //这句话很重要哈,表示字符串的结束,连\0也拷贝过去。
//上面的蓝色部分还可以简写为:while((*dst++ = *src++) != '\0');
return temp;
}
int main(void){
char *src ="this is a test of strcpy";
char dst[100];
char dst2[100] ="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
strcpy(dst,src);
strcpy(dst2,src);
printf("%s\n",dst);
printf("%s\n",dst2);
return 0;
}
//运行结果为:
this is a test of strcpy
this is a test of strcpy
Press any key to continue
5、不用库函数,实现C语言中的字符串拷贝charcpy()
最新推荐文章于 2022-10-28 20:26:26 发布