如何复制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字符串.
如果你想复制a
到b
那么只需使用= operator
.
string a = "text";
string b = "image";
b = a;
Run Code Online (Sandbox Code Playgroud)
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"
归档时间: |
|
查看次数: |
94209 次 |
最近记录: |