C语言实现字符串的复制的两种方法

利用数组实现

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 void copy_string(char str1[],char str2[])
 5 {
 6     int i = 0;
 7     while(str2[i] != '\0')
 8     {
 9         str1[i] = str2[i];
10         i++;
11     }
12     str1[i] = '\0';
13 }
14 
15 int main()
16 {
17     char a[100],b[100];
18     gets(a);
19     gets(b);
20     copy_string(a,b);
21     printf("%s\n",a);
22     return 0;
23 }

利用指针实现

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 void copy_string(char *p1,char *p2)
 5 {
 6     while(*p2 != '\0')
 7     {
 8         *p1 = *p2;
 9         *p1++;
10         *p2++;
11     }
12     *p1 = '\0';
13 }
14 
15 int main()
16 {
17     char a[100],b[100];
18     gets(a);
19     gets(b);
20     copy_string(a,b);
21     printf("%s\n",a);
22     return 0;
23 }

猜你喜欢

转载自www.cnblogs.com/wang1998/p/13189382.html