1.将字符串a的数据复制到字符串b中
(5.用for循环和指针来实现 )------注释掉部分采用的是此方法
#includeint main() { void copy_string(char from[], char to[]); char a[]="I am a student."; //char a[11]; //for (int i = 0; i < 10; i++) //{ // scanf("%c", &a[i]); //} char b[] = "You are a teacher."; printf("string a=%snstring b=%sn", a, b); printf("copy string a to string b:n"); copy_string(a, b); printf("nstring a=%snstring b=%sn", a, b); return 0; } void copy_string(char from[], char to[]) { int i = 0; while (from[i] != ' ') { to[i] = from[i]; i++; } to[i] = ' '; }
2.char * str_copy
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("%sn",p);
return 0;
}
char* str_copy1(char* d, char* s)
{
int i=0;
while (s[i] != ' ')
{
d[i] = s[i];
i++;
}
d[i] = ' ';
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++) != ' ');
return t;
}
char* str_copy3(char* d, char* s)
{
char* pd = d, * ps = s;
int i = 0, nd = 0, sd = 0;
while (*pd != ' ')
{ //计算目标字符串长度
nd++;
pd++;
}
while (*ps != ' ')
{ //计算源字符串长度
sd++;
ps++;
}
int dif = nd - sd; //地址差
if (dif < 0)
{
while (d[i] != ' ')
{
d[i] = s[i];
i++;
}
d[i] = ' ';
}
else {
while (s[i] != ' ')
{
d[i] = s[i];
i++;
}
d[i] = ' ';
}
return d;
}
3.数组的方式实现(访问下标)
#include4.使用指针解引用的方式实现//第一种方法:使用数组下标访问 void Copy1(char* des, char* src) { int i; for (i = 0; src[i] != ' '; i++)//当src[i]出现' '时,代表字符串遍历结束 { des[i] = src[i];//给des[i]赋值 } des[i] = ' ';//给复制好的des[i]的结尾加上' ',代表字符串的结束 } int main() { char arr[10] = "abcdefg"; char brr[10]; Copy1(brr, arr);//调用函数1 printf("holle world %s", brr);//输出复制好的字符串数组brr printf("n"); return 0; }
//第一种方法:使用指针解引用访问(原理:利用p[i]等价于*(p+i)) #includevoid Copy2(char* des, char* src) { int i; for (i = 0; *(src + i) != ' '; i++)//当src出现' '时,代表字符串遍历结束 { *(des + i) = *(src + i);//给des赋值 } *(des + i) = ' ';//给复制好的des的结尾加上' ',代表字符串的结束 } int main() { char arr[10] = "abcdefg"; char brr[10]; Copy2(brr, arr);//调用函数2 printf("holle world %s", brr);//输出复制好的字符串数组brr printf("n"); return 0; }
编著注:以上对本小题的代码编写的多种方法,欢迎大家收藏借鉴并转发;
以上代码仅供参考,如有问题欢迎大家在留言区批评指正;
版权所有,翻印必究,如有雷同纯属巧合,转载请注明出处。
By CRH380AJ2808 2022.06.09
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/JH13thpig/article/details/125183968
————————————————



