c语言三种方法把一个字符串复制到另一段字符串中

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

// 有一个字符数组a,在其中存放字符串“I am a boy.”,要求把该字符串复制到字符数组b 中。

/*

#include

int main()

{

char a[]="I am a boy.";

char b[20];

int i;

for(i=0;*(a+i)!='\0';i++)

{

*(b+i)=*(a+i); // 用地址法访问数组元素

}

*(b+i)='\0';

printf("string a is: %s\n",a);

printf("string b is:");

//for(i=0;b[i]!='\0';i++)

for(i=0;*(b+i)!='\0';i++)

{

//printf("%c",b[i]);

printf("%c",*(b+i));

}

printf("\n");

return 0;

}

*/

//用指针变量来实现

/*

#include

int main()

{

char a[]="I am a boy.";

char b[20],*p1,*p2;

int i;

p1=a;

p2=b;

for(;*p1!='\0';*p1++,*p2++)

{

*p2=*p1;

}

*p2='\0';

printf("sting a is:%s\n",a);

printf("string b is:");

//for(i=0;b[i]!='\0';i++)

for(i=0;*(b+i)!='\0';i++)

{

//printf("%c",b[i]);

printf("%c",*(b+i));

}

printf("\n");

return 0;

}

*/

// 用函数调用来实现

#include

int main()

{

void copy_string(char *from,char *to);

char *a="I am a teacher."; // 定义a为字符指针变量,指向一个字符串

char b[]="You are a student."; // 定义b为字符数组,内放一个字符串char *p=b; // 字符指针变量p指向字符数组b 的首元素

printf("string a=%s\nstring b=%s\n",a,p);

printf("\ncopy string a to string b:\n");

copy_string(a,p); // 用字符串做形参

printf("string a=%s\nstring b=%s\n",a,b);

return 0;

}

/*

void copy_string(char *from,char *to) // 形参是字符指针变量

{

for(;*from!='\0';from++,to++); // 只要a串没结束就复制到b数组

{

*to=*from;

}

*to='\0';

}

*/

/*

void copy_string(char *from,char *to)

{

while((*to=*from)!='\0')

{

to++;

from++;

}

}

*/

/*

void copy_string(char *from,char *to) {

while((*to++=*from++)!='\0'); }

*/

/*

void copy_string(char *from,char *to) {

while(*from!='\0')

*to++=*from++;

*to='\0';

}*/

void copy_string(char *from,char *to) {

char *p1,*p2;

p1=from;

p2=to;

while((*p2++=*p1++)!='\0');

}

相关文档
最新文档