C++ string 模仿QString arg

string拼接不管是书写还是易读性都比较差, 现模仿QString arg()的写法,实现简单的拼接,直接上代码

#include "stdafx.h"
#include <string>
#include <stdarg.h>
#include <iostream>
#include <vector>
using namespace std;

class qtString
{
public:
    //str 待格式化字符
	qtString(std::string  str) {
		mpQtString = this;
		mCount = 0;
		mString = str;
	}
    //返回格式化后的字符
	std::string getStdString()
	{
		return mString;
	}
    //参数 
	qtString arg(std::string param) {
		replace(param);
		mpQtString->mCount++;
		return *mpQtString;
	}
    //替换字符 根据qt里面的用%0 %1 ....代表需要替换的参数 
    //必须是由%0起始 可自行完善此缺陷
	void replace(std::string param)
	{
		auto key = "%" + to_string(mpQtString->mCount);
		auto index = mString.find(key);
		if (index < 0) return;
		auto temp = mString.substr(0, index);
		temp += param;
		mpQtString->mString = mString.replace(0, index+key.length(), temp);
	}

public:
	qtString* mpQtString;
	std::string mString;
    //%x 计数器 arg 调用一次 mCount加1
	int mCount;
	
};


int main()
{
	auto msg = qtString("insert into table tbl_user value('%0', '%1', '%2')").arg("测试").arg("男").arg("高1(3)班");
	std::cout << msg.getStdString() << std::endl;
	system("pause");
    return 0;
}

结果输出:

 此代码唯一缺陷原字符中必须有%0起始顺序累加,否者程序无法正常运作。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值