<script type="text/javascript"><!-- /*<![CDATA[*/ if(top.location != self.location){ top.location = self.location; } var myref = encodeURIComponent("http://hi.baidu.com/taney/blog/item/5aed5381a98caedbbc3e1eb8%2Ehtml"); /*]]>*/ // --></script>
0 前言: string 的角色C++ 語言是個十分優秀的語言,但優秀並不表示完美。還是有許多人不願意使用C或者C++,爲什麼?原因衆多,其中之一就是C/C++的文本處理功能太麻煩,用 起來很不方便。以前沒有接觸過其他語言時,每當別人這麼說,我總是不屑一顧,認爲他們根本就沒有領會C++的精華,或者不太懂C++,現在我接觸 perl, php, 和Shell腳本以後,開始理解了以前爲什麼有人說C++文本處理不方便了。舉例來說,如果文本格式是:用戶名 電話號碼,文件名name.txt Tom 23245332Jenny 22231231Heny 22183942Tom 23245332... 那麼在shell 編程 中,可以這樣用: awk '{print $1} ' name.txt | sort | uniq 如果使用C/C++ 就麻煩了,他需要做以下工作:
當然,有了STL,這些處理會得到很大的簡化。我們可以使用 fstream來代替麻煩的fopen fread fclose, 用vector 來代替數組。最重要的是用 string 來代替char * 數組,使用sort排序算法 來排序,用unique 函數 來去重。聽起來好像很不錯 。看看下面代碼(例程1): #include<string>
當然,在這個文本格式中,不用vector而使用map會更有擴充性,例如,還可通過人名找電話號碼等等,但是使用了map就不那麼好用sort了。你可以用map試一試。 這裏string的作用不只是可以存儲字符串,還可以提供字符串的比較,查找等。在sort和unique函數中就默認使用了less 和equal_to函數, 上面的一段代碼,其實使用了string的以下功能:
總之,有了string 後,C++的字符文本處理功能總算得到了一定補充,加上配合STL其他容器使用,其在文本處理上的功能已經與perl, shell, php的距離縮小很多了。 因此掌握string 會讓你的工作事半功倍。
1 string 使用其實,string並不是一個單獨的容器,只是basic_string 模板類的一個typedef 而已,相對應的還有wstring, 你在string 頭文件中你會發現下面的代碼:extern"C++"
string 其實相當於一個保存字符的序列容器,因此除了有字符串的一些常用操作以外,還有包含了所有的序列容器的操作。字符串的常用操作包括:增加、刪除、修改、查找比較、鏈接、輸入、輸出等。詳細函數列表參看附錄 。不要害怕這麼多函數,其實有許多是序列容器帶有的,平時不一定用的上。 如果你要想了解所有函數的詳細用法,你需要查看basic_string ,或者下載STL編程手冊 。這裏通過實例介紹一些常用函數。 1.1 充分使用string 操作符string 重載了許多操作符,包括 +, +=, <,=,
, [], <<, >>等,正式這些操作符,對字符串操作非常方便。先看看下面這個例子:tt.cpp(例程2)
#include<string>
下面是程序的輸出 -bash-2.05b$ make ttc++ -O -pipe -march=pentiumpro tt.cpp -o string, int > mymap;//以上默認使用了 less<string> string strinfo="Winter";
有了操作符以後,assign(), append(), compare(), at()等函數,除非有一些特殊的需求時,一般是用不上。當然at()函數還有一個功能,那就是檢查下標是否合法,如果是使用: string str="winter";//下面一行有可能會引起程序中斷錯誤 str[100]='!';//下面會拋出異常:throws: out_of_range cout<<str.at(100)<<endl; 1.2 眼花繚亂的string find 函數由於查找是使用最爲頻繁的功能之一,string 提供了非常豐富的查找函數。其列表如下:
size_type find_first_of(const basic_string& s, size_type pos = 0) template<class _CharT, class _Traits, class _Alloc> const
basic_string<_CharT,_Traits,_Alloc> ::size_type basic_string<_CharT,_Traits,_Alloc> ::npos = basic_string<_CharT,_Traits,_Alloc> ::size_type -1; find 和 rfind 都還比較容易理解,一個是正向匹配,一個是逆向匹配,後面的參數pos都是用來指定起始查找位置。對於find_first_of 和find_last_of 就不是那麼好理解。 find_first_of 是給定一個要查找的字符集,找到這個字符集中任何一個字符所在字符串中第一個位置。或許看一個例子更容易明白。 有這樣一個需求:過濾一行開頭和結尾的所有非英文字符。看看用string 如何實現: #include<string>
#include<iostream> using namespace std; int main() { string strinfo="//*---Hello Word!......------"; string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int first = strinfo.find_first_of(strset); int last = strinfo.find_last_of(strset);
這裏把所有的英文字母大小寫作爲了需要查找的字符集,先查找第一個英文字母的位置,然後查找最後一個英文字母的位置,然後用substr 來的到中間的一部分,用於輸出結果。下面就是其結果:
if(first ==-1)&&(last ==-1) ) cout<<"not find any characters,the result is incorect!"<<endl; cout << strinfo.substr(first, last - first + 1)<<endl; return 0; } Hello Word 張三|3456123, 湖南李四,4564234| 湖北王小二, 4433253|北京... 1.3 string insert, replace, erase瞭解了string 的操作符,查找函數和substr,其實就已經瞭解了string的80%的操作了。insert函數, replace函數和erase函數在使用起來相對簡單。下面以一個例子來說明其應用。string只是提供了按照位置和區間的replace函數,而不能用一個string字串來替換指定string中的另一個字串。這裏寫一個函數來實現這個功能: void string_replace(string & strBig, const string & strsrc, const string &strdst)
看看如何調用:
{ string::size_type pos=0; string::size_type srclen=strsrc.size(); string::size_type dstlen=strdst.size(); while( (pos=strBig.find(strsrc, pos))) != pos += dstlen; } #include<string>
其輸出結果:
#include<iostream> using namespace std; int main() { string strinfo="This is Winter, Winter is a programmer. Do you know Winter?"; cout<<"Orign string is :/n"<<strinfo<<endl; string_replace(strinfo, "Winter", "wende"); cout<<"After replace Winter with wende, the string is :/n"<<strinfo<<endl; return 0; } Orign string is :This is Winter, Winter is a programmer. Do you know Winter?
如果不用replace函數,則可以使用erase和insert來替換,也能實現string_replace函數的功能:
After replace Winter with wende, the string is :This is wende, wende is a programmer. Do you know wende? void string_replace(string & strBig, const string & strsrc, const string &strdst)
當然,這種方法沒有使用replace來得直接。
{ string::size_type pos=0; string::size_type srclen=strsrc.size(); string::size_type dstlen=strdst.size(); while( (pos=strBig.find(strsrc, pos))!=strBig.insert(pos, strdst)) pos += dstlen; } 2 string 和 C風格字符串現在看了這麼多例子,發現const char* 可以和string 直接轉換,例如我們在上面的例子中,使用string_replace(strinfo, "Winter ", "wende"); void string_replace(string & strBig, const string & strsrc, const string &strdst)
在C語言中只有char* 和 const char*,爲了使用起來方便,string提供了三個函數滿足其要求:
const charT* c_str() const
const charT* c_str () const
原來c_str()的流程是:先調用terminate(),然後在返回data()。因此如果你對效率要求比較高,而且你的處理又不一定需
要以/0的方式結束,你最好選擇data()。但是對於一般的C函數中,需要以const char*爲輸入參數,你就要使用c_str()函數。
{ if(length () == 0) return ""; terminate (); return data (); } 對於c_str() data()函數,返回的數組都是由string本身擁有,千萬不可修改其內容。其原因是許多string實現的時候採用了引用機制,也就是說,有可能幾 個string使用同一個字符存儲空間。而且你不能使用sizeof(string)來查看其大小。詳細的解釋和實現查看Effective STL 的條款15:小心string實現的多樣性 。 另外在你的程序中,只在需要時才使用c_str()或者data()得到字符串,每調用一次,下次再使用就會失效,如: string strinfo("this is Winter ");...//最好的方式是: foo(strinfo.c_str());//也可以這麼用: const char * pstr=strinfo.c_str();foo(pstr);//不要再使用了pstr了, 下面的操作已經使pstr無效了。 strinfo += " Hello! ";foo(pstr);//錯誤! 會遇到什麼錯誤?當你幸運的時候pstr可能只是指向"this is Winter Hello!"的字符串, 3 string 和 Charactor Traits瞭解了string的用法,該詳細看看string的真相了。前面提到string 只是basic_string的一個typedef。看看basic_string 的參數:template<class charT, class traits = char_traits<charT>,class Allocator = allocator<charT> >class basic_string
就像Steve Donovan在過度使用C++模板 中提到的,這些確實有些過頭了,要不是系統自己定義了相關的一些屬性,而且用了個typedef,否則還真不知道如何使用。 但複雜總有複雜道理。有了char_traits,你可以定義自己的字符串類型。當然,有了char_traits < char > 和char_traits < wchar_t > 你的需求使用已經足夠了,爲了更好的理解string ,咱們來看看char_traits都有哪些要求。 如果你希望使用你自己定義的字符,你必須定義包含下列成員的結構:
現在默認的string版本中,並不支持忽略大小寫的比較函數和查找函數,如果你想練練手,你可以試試改寫一個char_traits , 然後生成一個case_string類, 也可以在string 上做繼承,然後派生一個新的類,例如:ext_string,提供一些常用的功能,例如:
4 string 建議使用string 的方便性就不用再說了,這裏要重點強調的是string的安全性。
5 小結難怪有人說:string 使用方便功能強,我們一直用它!
6 附錄string 函數列表
7 參考文章 |