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

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

使用"+"运算符进行拼接:

std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2;  // 结果为"Hello World"

使用append()函数进行拼接:

std::string str1 = "Hello";
std::string str2 = "World";
str1.append(" ").append(str2);  // 结果为"Hello World"

使用+=运算符进行拼接:

std::string str1 = "Hello";
std::string str2 = "World";
str1 += " ";
str1 += str2;  // 结果为"Hello World"

使用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"

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

阅读剩余
THE END