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;
}
复制代码

 

posted @   十一的杂文录  阅读(812)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示