c++

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

小亿
131
2023-10-14 00:13:07
栏目: 编程语言
C++开发者专用服务器,限时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语言字符串拼接的方式有哪几种

0
看了该问题的人还看了