编写一个函数,实现字符串的复制,函数首部定义为:char * str_copy(char *d, char *s)
函数功能为:
将第二个参数s所表示的字符串复制到第一个参数d所表示的字符串中,函数返回值为第一个参数的值。
请写出完整的函数,并写出主函数,对该函数进行验证。
说明:本题不允许使用string.h中的标准函数,不允许改变函数首部
char * str_copy1(char *d, char *s);
char * str_copy2(char *d, char *s);
char * str_copy3(char *d, char *s);
int main(void){
char d[] = "qwerrt";
char s[] = "asdf213";
char *p;
//p = str_copy1(d,s);
//p = str_copy2(d,s);
p = str_copy3(d,s);
puts(p);
// printf("%s\n",p);
return 0;
}
char * str_copy1(char *d, char *s){
int i;
while(s[i]!='\0'){
d[i] = s[i];
i++;
}
d[i]='\0';
return d;
}
char * str_copy2(char *d, char *s){
if(d == NULL || s == NULL)
return NULL;
if(d == s)
return d;
char *t = d ;
while( (*d++ = *s++) != '\0');
return t ;
}
char * str_copy3(char *d, char *s){
char *pd=d,*ps=s;
int i=0,nd=0,sd=0;
while(*pd!='\0'){ //计算目标字符串长度
nd++;
pd++;
}
while(*ps!='\0'){ //计算源字符串长度
sd++;
ps++;
}
int dif=nd-sd; //地址差
if (dif<0){
while(d[i]!='\0'){
d[i] = s[i];
i++;
}
d[i]='\0';
}else{
while(s[i]!='\0'){
d[i] = s[i];
i++;
}
d[i]='\0';
}
return d;
}