很多時候我都想在自已的代碼中全部使用std::string代替MS的CString來保證我的程式在未來易於移植,但老實說CString比std::string好用很多,每每還是被誘惑了;再看看C#的string,用起來感覺更好。不過有了這個庫 我可以基本抵制住誘惑了...
#include <boost/algorithm/string.hpp>
很多時候我都想在自已的代碼中全部使用std::string代替MS的CString來保證我的程式在未來易於移植,但老實說CString比std::string好用很多,每每還是被誘惑了;再看看C#的string,用起來感覺更好。不過有了這個庫 我可以基本抵制住誘惑了 。
來看看有哪些不錯的東西,文檔上列出了下面的目錄(我改變了一下順序,有些基本的,大家都能猜到是什麼,這裡就不多說了)
1.Trimming
2.Case conversion
3.Replace Algorithms
4.Find Iterator
5.Find algorithms
6.Predicates and Classification
7.Split
對6.Predicates and Classification和7.Split我是比較感興趣的,先看看函數的列表(函數名有首碼i的是指對大 小寫不敏感)。
6.1.Predicates
starts_with // 'Starts with' predicate
istarts_with // 'Starts with' predicate ( case insensitive )
ends_with
iends_with
contains
icontains
equals
iequals
all
6.2.Classification
類屬斷言被加入到庫中主要是為了在使用演算法trim()和all()可以有一些便利 :-),其實差不多形式的函數STL都有,但都是對字元而言。
is_space // 空格
is_alnum // 字母和數字
is_alpha // 字母
is_cntrl // 控制字元
is_digit // 數字
is_graph // 可列印字元(不含空格)
is_lower // 小寫
is_print // 可列印字元(含空格)
is_punct // 標點
is_upper // 大寫
is_xdigit // 16進位數字
is_any_of //
...
例:
string str = "boost_1_32_0.rar";
cout << str
<< (boost::algorithm::ends_with(str, ".rar") ? "是": "不是") << "rar檔案" << endl;
例:
char text[]="hello world! ";
cout
<< text
<< (all( text, is_lower() )? "is": "is not")
<< " written in the lower case"
<< endl;
// prints "hello world! is not written in the lower case"
7.Split
find_all
ifind_all
split
split是一個我很喜歡的功能,C#中的string就有這個功能,下面是一段msdn中C#的代碼
string words = "this is a list of words, with: a bit of punctuation.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':'});
foreach (string s in split)
{
if (s.Trim() != "")
Console.WriteLine(s);
}
用起來感覺不錯的。 現在有了這個庫我們也可以這樣使用
string words = "this is a list of words, with: a bit of punctuation.";
vector<string> splitVec;
split( splitVec, words, is_any_of(" ,.:") );
for(int i=0; i<(int)splitVec.size(); i++)
{
if(trim_copy(splitVec[i]) != "")// 注意去掉空格,文檔中的例子沒做說明
cout << splitVec[i] << endl;
}
感覺與上面的差不多吧,呵,當樣,這樣寫也不錯
string words = "this is a list of words, with: a bit of punctuation.";
vector<string> splitVec;
boost::array<char, 4>separator = {' ', ',', '.', ':'};
//char separator[4] = {' ', ',', '.', ':'}; 也可
split( splitVec, words, is_any_of(separator) );
for(vector<string>::iterator iter=splitVec.begin(); iter!=splitVec.end(); ++iter)
{
if(!all(*iter, is_space()))
cout << *iter << endl;
}
到這裡,可以說基本的操作都有了,也比較好用。只是由於不是跟std::string放在一起,使用上稍稍感到麻煩,不過用名字空間,現在的IDE都能有效協助你,如果你是用VI那就另說了
前面大家看到不少功能,但還有一個重要的string操作大家沒看到,就是CString中常用的format方法 boost也提供了一個,但感覺上是比較變態的,下篇文章會做一個介紹。