欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

更優(yōu)雅的C++字符串格式化實(shí)現(xiàn)方法詳解

 更新時(shí)間:2023年04月19日 11:13:04   作者:愛(ài)吃肉的魚(yú)  
在用C++編寫(xiě)代碼時(shí),經(jīng)常需要用到字符串拼接及格式化,尤其是在拼寫(xiě)sql語(yǔ)句時(shí)。所以本文為大家介紹了更優(yōu)雅的C++字符串格式化實(shí)現(xiàn)方法,希望對(duì)大家有所幫助

背景

在用C++編寫(xiě)代碼時(shí),經(jīng)常需要用到字符串拼接及格式化,尤其是在拼寫(xiě)sql語(yǔ)句時(shí),目前大部分sql拼接方式都是通過(guò)ostringstream流一點(diǎn)一點(diǎn)拼接的,代碼可讀性很差而且很容易拼接錯(cuò)誤

    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) << "')";

優(yōu)化

參考python字符串格式化方式

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

先寫(xiě)出完整的字符串,在需要替換的位置通過(guò)占位符{}保留, 最后將占位符替換為指定的參數(shù)

實(shí)現(xiàn)

本質(zhì)是基于遞歸依次將字符轉(zhuǎn)中的占位符{}替換為對(duì)應(yīng)的參數(shù)

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++實(shí)現(xiàn)python風(fēng)格字符串格式化
    */
    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);

到此這篇關(guān)于更優(yōu)雅的C++字符串格式化實(shí)現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)C++字符串格式化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C++編程中刪除運(yùn)算符與相等運(yùn)算符的使用解析

    C++編程中刪除運(yùn)算符與相等運(yùn)算符的使用解析

    這篇文章主要介紹了C++編程中刪除運(yùn)算符與相等運(yùn)算符的使用解析,delete和==以及!=運(yùn)算符的使用是C++入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2016-01-01
  • C++中sort()函數(shù)和priority_queue容器中比較函數(shù)的區(qū)別詳析

    C++中sort()函數(shù)和priority_queue容器中比較函數(shù)的區(qū)別詳析

    C++中sort()和priority_queue都能自定義比較函數(shù),其中sort()自定義的比較函數(shù)比較好理解,priority_queue中自定義的比較函數(shù)的效果和sort()是相反的,這篇文章主要給大家介紹了關(guān)于C++中sort()函數(shù)和priority_queue容器中比較函數(shù)的區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • 基于C++實(shí)現(xiàn)職工管理系統(tǒng)

    基于C++實(shí)現(xiàn)職工管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了基于C++實(shí)現(xiàn)職工管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • 聊一聊C++虛函數(shù)表的問(wèn)題

    聊一聊C++虛函數(shù)表的問(wèn)題

    C++是面向?qū)ο蟮恼Z(yǔ)言(與C語(yǔ)言主要區(qū)別),所以C++也擁有多態(tài)的特性。下面通過(guò)代碼看下C++虛函數(shù)表的問(wèn)題,感興趣的朋友一起看看吧
    2021-10-10
  • C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)

    C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)

    下面小編就為大家?guī)?lái)一篇C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-03-03
  • C++中4種類型轉(zhuǎn)換方式 cast操作詳解

    C++中4種類型轉(zhuǎn)換方式 cast操作詳解

    static_cast,支持子類指針到父類指針的轉(zhuǎn)換,并根據(jù)實(shí)際情況調(diào)整指針的值,反過(guò)來(lái)也支持,但會(huì)給出編譯警告,它作用最類似C風(fēng)格的“強(qiáng)制轉(zhuǎn)換”,一般來(lái)說(shuō)可認(rèn)為它是安全的
    2013-10-10
  • C語(yǔ)言實(shí)現(xiàn)哈夫曼樹(shù)

    C語(yǔ)言實(shí)現(xiàn)哈夫曼樹(shù)

    這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)哈夫曼樹(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • c++中string和vector的詳細(xì)介紹

    c++中string和vector的詳細(xì)介紹

    這篇文章主要介紹了c++中string和vector的詳細(xì)介紹,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下
    2022-09-09
  • 使用VC6.0對(duì)C語(yǔ)言程序進(jìn)行調(diào)試的基本手段分享

    使用VC6.0對(duì)C語(yǔ)言程序進(jìn)行調(diào)試的基本手段分享

    這篇文章主要介紹了用VC6.0開(kāi)發(fā)c語(yǔ)言程序的時(shí)候調(diào)試代碼的一些小技巧,需要的朋友可以參考下
    2013-07-07
  • 在while中使用cin>>a?為條件及注意事項(xiàng)說(shuō)明

    在while中使用cin>>a?為條件及注意事項(xiàng)說(shuō)明

    這篇文章主要介紹了在while中使用cin>>a?為條件及注意事項(xiàng)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07

最新評(píng)論