优秀的boost字符串处理

我将把我认为非常有用,C++标准库又不是特别完备的做下重新学习做下笔记:字符串处理,文件系统等

在C++03中字符串的处理相当不灵活

对比MFC的CString的实现,我们可以发现string不仅缺少了分词的tokenizer, 替换字符串的replace也没有实现根据输入子串的替换,不仅没有format还缺少了trim操作,可以说在最常用的地方少了许多便利性。虽然C++11增加了 to_string,stoi等转换函数,但依旧显得单薄。


而boost针对这点增加了许多实用的工具:

下面记得是format,使用起来相当方面只需要包含相关头文件即可使用

format可以提供格式化字符串的操作,同时该类提供了类型检查功能,使用起来则相当方便

format本身重载了operator<<操作符,可以直接输出到想要的流中;

如:

format("%d,%s")

在指定数据时使用有点变化,以%输入所需数据

上面可表示为

format(”%d,%s“)%5%"Sef";

此外还可以有另一种像C#的位置的表示

format(” %1%,%2% “)  %5 %”Sef"


还有点非常有用如下,包括str函数

    cout <<  format("_%1$4d_ is : _%1$#4x_, _%1$#4o_, and _%1$s_ by default\n")  % 18;
    //          prints  "_  18_ is : _0x12_, _ 022_, and _18_ by default\n"

    // Taking the string value :
    std::string s;
    s= str( format(" %d %d ") % 11 % 22 );



由于format效率较低可以

使用copy来减少字符串解释时间

const format   fmt(”%,%s”);
format(fmt)%5%"Sef";

效率可以有个如下直观认识:

其中clockTime

#include <iostream>
#include <ctime>
using namespace std;

class clockTime{
public:
	clockTime(){
		clt_start = clock();
	}

	~clockTime(){
		cout << "time cost:\t"<<clock() - clt_start << endl;
	}

private:
	clock_t  clt_start;
};


测试代码:

void testProfile()
{
	{
		cout << "normal" << endl;
		clockTime te;
		for (int i = 0; i < 20000; ++i)
		{
			format("%d,%s") % 5 % "Sef";
		}
	}

	{
		cout << "copy" << endl;
		clockTime te;
		const format fmt("%d,%s");
		for (int i = 0; i < 20000; ++i)
		{
			format(fmt) % 5 % "Sef";
		}
	}
	{
		cout << "bind" << endl;
		clockTime te;
		const format fmt("%1%,%2%");
		for (int i = 0; i < 20000; ++i)
		{
			format(fmt) % 5 % "Sef";
		}
	}

	{
		char buf[10] = { 0 };
		cout << "sprintf" << endl;
		clockTime te;

		for (int i = 0; i < 20000; ++i)
		{
			sprintf_s(buf, 10, "%d,%s", 5, "Sef");
			string a = buf;
		}

	}

	{
		cout << "to_string" << endl;
		clockTime te;
		
		for (int i = 0; i < 20000; ++i)
		{
			string a = to_string(5);
			a += "Sef";
		}

	}

}

运行结果如下:


<a>


可以看到虽然sprintf使用起来不方便,但性能还是要好很多,如果使用format就尽量使用提前构造好,然后拷贝方式使用,从使用来说还是非常方便的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值