温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++字符串格式化怎么实现

发布时间:2023-04-19 14:26:10 来源:亿速云 阅读:94 作者:iii 栏目:开发技术

本篇内容主要讲解“C++字符串格式化怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++字符串格式化怎么实现”吧!

背景

在用C++编写代码时,经常需要用到字符串拼接及格式化,尤其是在拼写sql语句时,目前大部分sql拼接方式都是通过ostringstream流一点一点拼接的,代码可读性很差而且很容易拼接错误

    ostringstream sqlstr;
    sqlstr << "insert into virtual_item_info(id, platform, typeid, name, icon_url, act_url, "
              "desc_text, vm_typeid, vm_price, val_typeid, val_count, priority, show_type, param, "
              "combo, area, "
              "onshelf_time, offshelf_time, status, show_url, svga_url, mp4_url, remarks_info, "
              "shading_url, utime, has_green_dot, act_id, "
              "act_name, act_icon, act_name_lang_id, act_start_time, act_end_time, item_level, "
              "distribute_src, buy_to_use_duration, noble_lvl, name_lang_id, desc_lang_id, "
              "target_whitelist_id, target_whitelist_type, is_cp_shareable, act_link_type, "
              "act_show_type, item_lang_code)"
           << "values(" << item.id << "," << item.platform << "," << item.atypeid << ",'"
           << EscapeString(item.name) << "','" << EscapeString(item.iconurl) << "','"
           << EscapeString(item.actUrl) << "','" << EscapeString(item.desctext) << "',"
           << item.vmtypeid << "," << item.vmprice << "," << item.valtypeid << "," << item.valcount
           << "," << item.priority << "," << item.showType << ",'" << EscapeString(item.param)
           << "'," << item.isCombo << ",'" << EscapeString(item.area) << "',"
           << item.onshelftime << "," << item.offshelftime << "," << item.status << ",'"
           << EscapeString(item.showUrl) << "','" << EscapeString(item.svgaUrl) << "','"
           << EscapeString(item.mp4Url) << "','" << EscapeString(item.remarksInfo)
           << "', '" << EscapeString(item.shadingUrl) << "', " << butil::gettimeofday_s()
           << "," << item.hasGreenDot << ",'" << EscapeString(item.actId) << "','"
           << EscapeString(item.actName) << "','" << EscapeString(item.actIcon) << "','"
           << EscapeString(item.actNameLangId) << "'," << item.actStartTime << ","
           << item.actEndTime << "," << item.itemLevel << "," << item.distributeSrc << ","
           << item.buyToUseDuration << "," << item.nobleLevel << ",'"
           << EscapeString(item.nameLangId) << "','" << EscapeString(item.descLangId)
           << "','" << EscapeString(item.targetGroupWhiteListId) << "',"
           << item.targetGroupWhiteListType << "," << item.isCpShareable << "," << item.actLinkType
           << "," << item.actShowType << ",'" << EscapeString(item.itemLangCode) << "')";

优化

参考python字符串格式化方式

"{} {}".format("hello", "world")

先写出完整的字符串,在需要替换的位置通过占位符{}保留, 最后将占位符替换为指定的参数

实现

本质是基于递归依次将字符转中的占位符{}替换为对应的参数

class StringUtil {
private:
    // 递归出口
    static void BuildFormatString(std::ostringstream& builder,
                                  const std::string& fmt_spec,
                                  std::string::size_type idx) {
        builder.write(fmt_spec.data() + idx, fmt_spec.size() - idx);
    }


    template <typename T, typename... Types>
    static void BuildFormatString(std::ostringstream& builder,
                                  const std::string& fmt_spec,
                                  std::string::size_type idx,
                                  const T& first,
                                  const Types&... args) {
        auto pos = fmt_spec.find_first_of("{}", idx);a
        if (pos == std::string::npos) {
            builder.write(fmt_spec.data() + idx, fmt_spec.size() - idx);
            return;
        }

        builder.write(fmt_spec.data() + idx, pos - idx);
        builder << first;
        BuildFormatString(builder, fmt_spec, pos + 2, args...);
    }

public:
    /**
    * C++实现python风格字符串格式化
    */
    template <typename... Types>
    static std::string FormatString(const std::string& fmt_spec, const Types&... args) {
        std::ostringstream builder;
        BuildFormatString(builder, fmt_spec, 0, args...);
        return builder.str();
    }
};

使用

uint32_t ts = butil::gettimeofday_s();
string sql_formattor =
        "insert into tbl_user_relation_info(uid, gift_id, batch_id, relation_id, crc32_relation_id, status, peer_uid, relation_create_time, create_time, update_time, order_id) values({}, {}, {}, '', 0, 0, 0, 0, {}, {}, '{}')";
string sql = StringUtil::FormatString(sql_formattor, uid, giftId, batchId, ts, ts, orderId);

到此,相信大家对“C++字符串格式化怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI