【整理】字符串的拷贝有哪些方式,以及memcpy和strcpy的区别

字符串的拷贝有哪些方式,以及memcpy和strcpy的区别

1.字符串的拷贝有哪些方式

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     //方法一:逐个字符的赋值
 8     char s1[20] = "abc123";
 9     char s2[20];
10     for (int i = 0; i < 20; i++)
11         s2[i] = s1[i];
12     cout << "s1:" << s1 << endl;
13     cout<<"s2:" << s2<<endl;
14 
15     //方法二:直接赋值
16     string s3 = "abc123";
17     string s4;
18     s4 = s3;
19     cout << "s3:" <<s3<< endl;
20     cout << "s4:" << s4 << endl;
21 
22     //方法三:strcpy函数
23     string s5 = "abc123";
24     string s6;
25     char s7[20];
26     //strcpy(s6, s5);这样会报错
27     //strcpy(s6, s5.c_str());这样会报错
28     strcpy(s7, s5.c_str());
29     cout << "s5:" << s5<<endl;
30     cout << "s7:" << s7<<endl;
31     char s8[20] = "abc123";
32     char s9[20];
33     strcpy(s9, s8);
34     cout << "s8:" << s8 << endl;
35     cout << "s9:" << s9 << endl;
36 
37     //方法四:memcpy函数
38     char s10[20] = "abc123";
39     char s11[20];
40     memcpy(s11, s10,20);
41     cout << "s10:" << s10 << endl;
42     cout << "s11:" << s11<< endl;
43     char *p = "abc123";
44     char s12[20];
45     memcpy(s12, p, strlen(p) + 1);
46     cout << "s12:" << s12 << endl;
47 
48     system("pause");
49     return 0;
50 }
51 //注意:#include <cstring>   //不可以定义string s;可以用到strcpy等函数,cout<<s3会报错
52 //注意:#include <string>    //可以定义string s;可以用到strcpy等函数,cout<<s3不会报错

2.memcpy和strcpy的区别

  (1)复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。

  (2)复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符""才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。

  (3)用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy。
 

——如有不对的地方,非常欢迎给予指导!

原文地址:https://www.cnblogs.com/engraver-lxw/p/7620296.html