更優(yōu)雅的C++字符串格式化實(shí)現(xiàn)方法詳解
背景
在用C++編寫代碼時(shí),經(jīng)常需要用到字符串拼接及格式化,尤其是在拼寫sql語句時(shí),目前大部分sql拼接方式都是通過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")
先寫出完整的字符串,在需要替換的位置通過占位符{}保留, 最后將占位符替換為指定的參數(shù)
實(shí)現(xiàn)
本質(zhì)是基于遞歸依次將字符轉(zhuǎn)中的占位符{}替換為對應(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
OpenCV圖像特征提取之Shi-Tomasi角點(diǎn)檢測算法詳解
Harris角點(diǎn)檢測算法就是對角點(diǎn)響應(yīng)函數(shù)R進(jìn)行閾值處理,Shi-Tomasi原理幾乎和Harris一樣的,只不過最后計(jì)算角點(diǎn)響應(yīng)的公式發(fā)生了變化。本文將和大家詳細(xì)說說Shi-Tomasi角點(diǎn)檢測算法的原理與實(shí)現(xiàn),需要的可以參考一下2022-09-09
C語言結(jié)構(gòu)體嵌套與對齊超詳細(xì)講解
這篇文章主要介紹了C語言結(jié)構(gòu)體嵌套與對齊,C語言中結(jié)構(gòu)體是一種構(gòu)造類型,和數(shù)組、基本數(shù)據(jù)類型一樣,可以定義指向該種類型的指針。結(jié)構(gòu)體指針的定義類似其他基本數(shù)據(jù)類型的定義2022-12-12
C語言的進(jìn)制轉(zhuǎn)換及算法實(shí)現(xiàn)教程
這篇文章主要介紹了C語言的進(jìn)制轉(zhuǎn)換及算法實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
簡要對比C語言中的truncate()函數(shù)與ftruncate()函數(shù)
這篇文章主要介紹了C語言中的truncate()函數(shù)與ftruncate()函數(shù)的簡要對比,注意其之間的區(qū)別,需要的朋友可以參考下2015-09-09

