解题思路:定义一个函数copy_string 用来实现字符串复制的功能,在主函数中调用此函数,函数的形参和实参可以分别用字符数组名或字符指针变量。
(1)用字符数组名作为函数参数
#include <stdio.h>
int main()
{
void copy_string(char from[],char to[]);
char a[] = "I am a teacher.";
char b[] = "You are a student.";
printf("string a=%s\nstring b=%s\n", a, b);
printf("copy string a to string b:\n");
copy_string(a, b);
printf("\nstring a= %s\nstring b=%s\n", a, b);
return 0;
}
void copy_string(char from[], char to[])
{
int i = 0;
while (from[i] != '\0')
{
to[i] = from[i];
i++;
}
to[i] = '\0';
}
(2)用字符型指针变量作实参
#include<stdio.h>
int main()
{
void copy_string(char from[], char to[]);
char a[] = "I am a teacher.";
char b[] = "You are a student.";
char* from = a, * to = b;
printf("string a= %s\nstring b=%s\n",a, b);
printf("\ncopy string a to string b: \n");
copy_string(from, to);//字符型指针变量作品作实参
printf("string a=%s\nstring b=%s\n", a, b);
return 0;
}
void copy_string(char from[], char to[])
{
int i = 0;
while (from[i] != '\0')
{
to[i] = from[i];
i++;
}
to[i] = '\0';
}
程序分析:指针变量from的值是a数组首元素的地址,指针变量to的值是b数组首元素的地址。它们作为实参,把a数组首元素的地址和b数组首元素的地址传递给形参数组名from和 to(它们实质上也是指针变量),其他与程序(1)相同。
(3)用字符指针变量作形参和实参
#include<stdio.h>
int main()
{
void copy_string(char* from, char* to);
char* a = "I am a teacher.";
char b[] = "You are a student.";//定义b为字符数组
char* p = b;
printf("string a=%s\nstring b=%s\n", a, b);
printf("\ncopy string a to string b: \n");
copy_string(a, p);//通过p改变b
printf("string a=%s\nstring b=%s\n", a, b);
return 0;
}
void copy_string(char* from, char* to)
{
for (; *from != '\0'; from++, to++)
{
*to = *from;
}
*to = '\0';
}
程序改进:
(1)将copy_string函数改写为
void copy_string(char * from,char * to)
{while (( * to= * from)!='\0')
{to++;from++;}
这是先赋值后判断,免去了最后还要给*to赋空字符额外的一步。
(2) copy_string函数的函数体还可改为
{ while (( * to++= * from++)!='\0') ;}
将++放在了一起,即赋值判断后再各自++或者写成:{while ( * from!='\0')
*to++=* from++;* to='\0'; }
(3)由于字符可以用其ASCII 码来代替(例如,“ch='a'”可用“ch= 97”代替,“while(ch!='a')”可以用“while(ch!=97)因此,“while( * from!='\0')”可以用‘while( * from! =0)”代替('\0'的ASCII代码
而关系表达式“*from!=0”又可简化为*from”,这是因为* from的值不等于0,则表达式“* from”为真,同时“ * from!=0”也为真。因此“while( * from!=0)”和“while(* from)”是等价的。所以函数体可简化为
{ while ( * from)
* to++= * from++;*to='\0’;
}
以上的while语句还等价于:while(*to++=*from++)等价于:while((*to++=*from++)!='\0')
(4)也可以用字符数组名作函数形参,在函数中另定义两个指针变量pl,p2。函数copy_string可写为:
void copy_string(char from[],char to[])
{
char * p1,* p2;
pl=from; p2=to;
while(( * p2++=* p1++)!='\0');}