gpt4 book ai didi

c++ - c++中字符串类对象的+运算符和附加函数之间的区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:06 24 4
gpt4 key购买 nike

假设我们可以添加两个字符串类对象

string str1="hello"
string str2="world"

string final =str1+str2;

string f=str1.append(str2);

这两种方法有什么区别??他们添加或实现或其他任何东西的顺序??

最佳答案

operator+ 会将两个字符串相加并生成一个新的字符串。 append 将采用一个字符串并将其连接到字符串的末尾。

#include <iostream>
#include <string>
using namespace std;

int main ()
{
string str = "Writing";
string str2= " a book";
str.append(str2);
cout << str << endl; // "Writing a book"
return 0;
}

另外,append还有更多的特性,比如只追加那个字符串的一部分

#include <iostream>
#include <string>
using namespace std;

int main ()
{
string str;
string str2="Writing ";
string str3="print 10 and then 5 more";

// used in the same order as described above:
str.append(str2); // "Writing "
str.append(str3,6,3); // "10 "
str.append("dots are cool",5); // "dots "
str.append("here: "); // "here: "
str.append(10,'.'); // ".........."
str.append(str3.begin()+8,str3.end()); // " and then 5 more"
str.append<int>(5,0x2E); // "....."

cout << str << endl;
return 0;
}

更多关于 append在这里。

关于c++ - c++中字符串类对象的+运算符和附加函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com