#include <iostream>
#include <string>
int main() {
// 使用 + 操作符拼接字符串
std::string str1 = "Hello";
std::string str2 = "World";
std::string result1 = str1 + " " + str2;
std::cout << "使用 + 拼接: " << result1 << std::endl;
// 使用 += 操作符拼接字符串
std::string result2 = "Hello";
result2 += " ";
result2 += "World";
std::cout << "使用 += 拼接: " << result2 << std::endl;
// 使用 append 方法拼接字符串
std::string result3 = "Hello";
result3.append(" ").append("World");
std::cout << "使用 append 拼接: " << result3 << std::endl;
// 使用 stringstream 拼接字符串
std::stringstream ss;
ss << "Hello" << " " << "World";
std::string result4 = ss.str();
std::cout << "使用 stringstream 拼接: " << result4 << std::endl;
return 0;
}
使用 +
操作符拼接字符串:
+
操作符可以直接将两个 std::string
对象连接在一起,也可以连接一个 std::string
和一个 C 风格的字符串或字符。"Hello"
和 "World"
通过 +
操作符连接,并在中间添加了一个空格。使用 +=
操作符拼接字符串:
+=
操作符用于将一个字符串追加到另一个字符串的末尾。"Hello"
,然后分别用 +=
追加了空格和 "World"
。使用 append
方法拼接字符串:
append
是 std::string
类的一个成员函数,用于将一个字符串追加到当前字符串的末尾。"Hello"
,然后调用 append
方法依次追加了空格和 "World"
。使用 stringstream
拼接字符串:
std::stringstream
是一个非常灵活的工具,可以方便地进行字符串的格式化操作。stringstream
对象,并使用 <<
操作符将多个字符串片段插入到流中,最后通过 str()
方法获取拼接后的字符串。上一篇:c++容器
下一篇:c++ 引用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站