這里向大家介紹一個C++的字符串格式化庫,叫cpptempl,這個庫支持對字符串格式的條件,循環,變量插入。看上去很不錯,只不過其是基于boost庫的。
下面是一個例子:
// The text templatewstring text = L"I heart {$place}!" ;// Data to feed the template enginecpptempl::data_map data ;// {$place} => Okinawadata[L"place"] = cpptempl::make_data(L"Okinawa");// parse the template with the supplied data dictionarywstring result = cpptempl::parse(text, data) ;
輸出結果是:
I heart Okinawa!
是不是很方便?讓我們看一個更復雜的例子:
// You'd probably load this template from a file in real life.wstring text = L"<h3>Locations</h3><ul>" L"{% for place in places %}" L"<li>{$place}</li>" L"{% endfor %}" L"</ul>" ;// Create the list of itemscpptempl::data_list places;places.push_back(cpptempl::make_data(L"Okinawa"));places.push_back(cpptempl::make_data(L"San Francisco"));// Now set this in the data mapcpptempl::data_map data ;data[L"places"] = cpptempl::make_data(places);// parse the template with the supplied data dictionarywstring result = cpptempl::parse(text, data) ;
輸出結果是:
<h3>Locations</h3>
<ul>
<li>Okinawa</li>
<li>San Francisco</li>
</ul>
更為詳細的說明請到這里:http://bitbucket.org/ginstrom/cpptemplate/wiki/Home。
Google也有一個類似的庫叫ctemplate:http://code.google.com/p/google-ctemplate/ 提供相似的方法,你也可以試試看。與Google相對應的Java庫叫Hapax:http://code.google.com/p/hapax/。
下一篇 處理加了密碼的MDB文件