现在的位置: 首页 > 综合 > 正文

5、不用库函数,实现C语言中的字符串拷贝charcpy()

2013年09月11日 ⁄ 综合 ⁄ 共 743字 ⁄ 字号 评论关闭

//第一题,实现字符串的复制
//笔试题常考啊这个东西//////////
//函数原型为: 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

抱歉!评论已关闭.