std::string 拼接字符串
C++ 20 format
#include <iostream> #include <string> #include <format> using namespace std; int main() { /** C++20,让字符串拼接变的更简单 * 除了常规的 字符串,数字拼接,还支持宽字符,以及各种格式 * {:d} 显示整数 * {:.2f} 两位小数 * {:>10} 宽度10,右对齐 * {"<10} 宽度10,左对齐 * {:^10} 宽度10,居中对齐 * {:,} 数字,千位分隔符 * {:.2%} 数字,百分比格式化 */ int width = 1920; int height = 1080; string s1 = format("width:{}, height:{}", width, height); string s2 = format("name:{}, age:{}", "zhangsan", 19); cout << s1 << endl; cout << s2 << endl; }
之前老的方法
#include <iostream> #include <string> #include <sstream> int main() { // 方法一:123456-==- std::string a = "123"; std::string b = "456"; std::string c; c.append(a).append(b).append("-==-"); std::cout << c << std::endl; // 方法二: std::string a1 = "123"; std::stringstream c1; c1 << 456 << "-==-"; a1 += c1.str(); std::cout << a1 << std::endl; }


浙公网安备 33010602011771号