c++字符串拼接的方式有哪几种

c++
1024
2023/10/13 0:13:07
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,有以下几种字符串拼接的方式:

  1. 使用"+"运算符进行拼接:
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2;  // 结果为"Hello World"
  1. 使用append()函数进行拼接:
std::string str1 = "Hello";
std::string str2 = "World";
str1.append(" ").append(str2);  // 结果为"Hello World"
  1. 使用+=运算符进行拼接:
std::string str1 = "Hello";
std::string str2 = "World";
str1 += " ";
str1 += str2;  // 结果为"Hello World"
  1. 使用sprintf()函数进行拼接:
char buffer[100];
std::string str1 = "Hello";
std::string str2 = "World";
sprintf(buffer, "%s %s", str1.c_str(), str2.c_str());
std::string result(buffer);  // 结果为"Hello World"

需要注意的是,以上方式中字符串的拼接都是在内存中创建一个新的字符串对象来存储拼接后的结果,而不是在原有字符串对象上直接修改。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++能否让动态编译更加智能化