如何复制2个字符串数据类型的字符串

Muh*_*aid 25 c++ string

如何复制2个字符串(这里我的意思是字符串数据类型).我使用了strcpy函数,它只适用于

char a[7]="text";
char b[5]="image";
strcpy(a,b);
Run Code Online (Sandbox Code Playgroud)

但每当我使用时

string a="text";
string b="image";
strcpy(a,b);
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

functions.cpp没有匹配函数来调用`strcpy(std :: string&,std :: string&)

Cae*_*sar 40

你不应该使用strcpy来复制std :: string,只能将它用于C-Style字符串.

如果你想复制ab那么只需使用= operator.

string a = "text";
string b = "image";
b = a;
Run Code Online (Sandbox Code Playgroud)

  • 对于strcat,你可以使用+ ="image" (3认同)

bam*_*s53 11

strcpy仅适用于C字符串.对于std :: string,您可以像任何C++对象一样复制它.

std::string a = "text";
std::string b = a; // copy a into b
Run Code Online (Sandbox Code Playgroud)

如果要连接字符串,可以使用+运算符:

std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;
Run Code Online (Sandbox Code Playgroud)

你甚至可以一次做很多事:

std::string c = a + " " + b + "hello";
Run Code Online (Sandbox Code Playgroud)

虽然"hello" + " world"不像你想象的那样有效.你需要一个显式的std :: string:std::string("Hello") + "world"