詳細解說STL string
0 前言: string 的角色
C++ 語言是個十分優秀的語言,但優秀并不表示完美。還是有許多人不愿意使用C或者C++,為什么?原因眾多,其中之一就是C/C++的文本處理功能太麻煩,用起來很不方便。以前沒有接觸過其他語言時,每當別人這么說,我總是不屑一顧,認為他們根本就沒有領會C++的精華,或者不太懂C++,現在我接觸perl, php, 和Shell腳本以后,開始理解了以前為什么有人說C++文本處理不方便了。舉例來說,如果文本格式是:用戶名 電話號碼,文件名name.txt BeautifierPlugin Error: Unable to handle "bash" syntax.
Tom 23245332 Jenny 22231231 Heny 22183942 Tom 23245332 ...
那么在shell 編程中,可以這樣用: BeautifierPlugin Error: Unable to handle "bash" syntax.
awk '{print $1}' name.txt | sort | uniq
如果使用C/C++ 就麻煩了,他需要做以下工作:
- 先打開文件,檢測文件是否打開,如果失敗,則退出。
- 聲明一個足夠大得二維字符數組或者一個字符指針數組
- 讀入一行到字符空間
- 然后分析一行的結構,找到空格,存入字符數組中。
- 關閉文件
- 寫一個排序函數,或者使用寫一個比較函數,使用qsort排序
- 遍歷數組,比較是否有相同的,如果有,則要刪除,copy...
- 輸出信息
當然,有了STL,這些處理會得到很大的簡化。我們可以使用 fstream來代替麻煩的fopen fread fclose, 用vector 來代替數組。最重要的是用 string來代替char * 數組,使用sort排序算法來排序,用unique 函數來去重。聽起來好像很不錯 。看看下面代碼(例程1):
#include <string> #include <iostream> #include <algorithm> #include <vector> #include <fstream> using namespace std; int main(){ ifstream in("name.txt"); string strtmp; vector<string> vect; while(getline(in, strtmp, '\n')) vect.push_back(strtmp.substr(0, strtmp.find(' '))); sort(vect.begin(), vect.end()); vector<string>::iterator it=unique(vect.begin(), vect.end()); copy(vect.begin(), it, ostream_iterator<string>(cout, "\n")); return 0; }
當然,在這個文本格式中,不用vector而使用map會更有擴充性,例如,還可通過人名找電話號碼等等,但是使用了map就不那么好用sort了。你可以用map試一試。
這里string的作用不只是可以存儲字符串,還可以提供字符串的比較,查找等。在sort和unique函數中就默認使用了less 總之,有了string 后,C++的字符文本處理功能總算得到了一定補充,加上配合STL其他容器使用,其在文本處理上的功能已經與perl, shell, php的距離縮小很多了。 因此掌握string 會讓你的工作事半功倍。
string 其實相當于一個保存字符的序列容器,因此除了有字符串的一些常用操作以外,還有包含了所有的序列容器的操作。字符串的常用操作包括:增加、刪除、修改、查找比較、鏈接、輸入、輸出等。詳細函數列表參看附錄。不要害怕這么多函數,其實有許多是序列容器帶有的,平時不一定用的上。
如果你要想了解所有函數的詳細用法,你需要查看basic_string,或者下載STL編程手冊。這里通過實例介紹一些常用函數。
下面是程序的輸出 BeautifierPlugin Error: Unable to handle "bash" syntax.
有了這些操作符,在STL中仿函數都可以直接使用string作為參數,例如 less, great, equal_to 等,因此在把string作為參數傳遞的時候,它的使用和int 或者float等已經沒有什么區別了。例如,你可以使用:
有了操作符以后,assign(), append(), compare(), at()等函數,除非有一些特殊的需求時,一般是用不上。當然at()函數還有一個功能,那就是檢查下標是否合法,如果是使用:
find 和 rfind 都還比較容易理解,一個是正向匹配,一個是逆向匹配,后面的參數pos都是用來指定起始查找位置。對于find_first_of 和find_last_of 就不是那么好理解。
find_first_of 是給定一個要查找的字符集,找到這個字符集中任何一個字符所在字符串中第一個位置。或許看一個例子更容易明白。
有這樣一個需求:過濾一行開頭和結尾的所有非英文字符。看看用string 如何實現:
string只是提供了按照位置和區間的replace函數,而不能用一個string字串來替換指定string中的另一個字串。這里寫一個函數來實現這個功能:
對于c_str() data()函數,返回的數組都是由string本身擁有,千萬不可修改其內容。其原因是許多string實現的時候采用了引用機制,也就是說,有可能幾個string使用同一個字符存儲空間。而且你不能使用sizeof(string)來查看其大小。詳細的解釋和實現查看Effective STL的條款15:小心string實現的多樣性。
另外在你的程序中,只在需要時才使用c_str()或者data()得到字符串,每調用一次,下次再使用就會失效,如:
就像Steve Donovan在過度使用C++模板中提到的,這些確實有些過頭了,要不是系統自己定義了相關的一些屬性,而且用了個typedef,否則還真不知道如何使用。
但復雜總有復雜道理。有了char_traits,你可以定義自己的字符串類型。當然,有了char_traits < char > 和char_traits < wchar_t > 你的需求使用已經足夠了,為了更好的理解string ,咱們來看看char_traits都有哪些要求。
如果你希望使用你自己定義的字符,你必須定義包含下列成員的結構:
現在默認的string版本中,并不支持忽略大小寫的比較函數和查找函數,如果你想練練手,你可以試試改寫一個char_traits , 然后生成一個case_string類, 也可以在string 上做繼承,然后派生一個新的類,例如:ext_string,提供一些常用的功能,例如:
1 string 使用
其實,string并不是一個單獨的容器,只是basic_string 模板類的一個typedef 而已,相對應的還有wstring, 你在string 頭文件中你會發現下面的代碼:
extern "C++" {
typedef basic_string <char> string;
typedef basic_string <wchar_t> wstring;
} // extern "C++"
1.1 充分使用string 操作符
string 重載了許多操作符,包括 +, +=, <, =,
, [], <<, >>等,正式這些操作符,對字符串操作非常方便。先看看下面這個例子:tt.cpp(例程2)
#include <string>
#include <iostream>
using namespace std;
int main(){
string strinfo="Please input your name:";
cout << strinfo ;
cin >> strinfo;
if( strinfo == "winter" )
cout << "you are winter!"<<endl;
else if( strinfo != "wende" )
cout << "you are not wende!"<<endl;
else if( strinfo < "winter")
cout << "your name should be ahead of winter"<<endl;
else
cout << "your name should be after of winter"<<endl;
strinfo += " , Welcome to China!";
cout << strinfo<<endl;
cout <<"Your name is :"<<endl;
string strtmp = "How are you? " + strinfo;
for(int i = 0 ; i < strtmp.size(); i ++)
cout<<strtmp[i];
return 0;
}
-bash-2.05b$ make tt
c++ -O -pipe -march=pentiumpro tt.cpp -o tt
-bash-2.05b$ ./tt
Please input your name:Hero
you are not wende!
Hero , Welcome to China!
How are you? Hero , Welcome to China!
map<string, int> mymap;
//以上默認使用了 less<string>
string strinfo="Winter";
string strlast="Hello " + strinfo + "!";
//你還可以這樣:
string strtest="Hello " + strinfo + " Welcome" + " to China" + " !";
由于這個等式是由左到右開始檢測執行,如果開始兩項都是const char* ,程序自己并沒有定義兩個const char* 的加法,編譯的時候肯定就有問題了。
string str="winter";
//下面一行有可能會引起程序中斷錯誤
str[100]='!';
//下面會拋出異常:throws: out_of_range
cout<<str.at(100)<<endl;
1.2 眼花繚亂的string find 函數
由于查找是使用最為頻繁的功能之一,string 提供了非常豐富的查找函數。其列表如下:
以上函數都是被重載了4次,以下是以find_first_of 函數為例說明他們的參數,其他函數和其參數一樣,也就是說總共有24個函數
函數名
描述
find
查找
rfind
反向查找
find_first_of
查找包含子串中的任何字符,返回第一個位置
find_first_not_of
查找不包含子串中的任何字符,返回第一個位置
find_last_of
查找包含子串中的任何字符,返回最后一個位置
find_last_not_of
查找不包含子串中的任何字符,返回最后一個位置
:
size_type find_first_of(const basic_string& s, size_type pos = 0)
size_type find_first_of(const charT* s, size_type pos, size_type n)
size_type find_first_of(const charT* s, size_type pos = 0)
size_type find_first_of(charT c, 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;
#include <string>
#include <iostream>
using namespace std;
int main(){
string strinfo=" //*---Hello Word!......------";
string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int first = strinfo.find_first_of(strset);
if(first == string::npos) {
cout<<"not find any characters"<<endl;
return -1;
}
int last = strinfo.find_last_of(strset);
if(last == string::npos) {
cout<<"not find any characters"<<endl;
return -1;
}
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函數在使用起來相對簡單。下面以一個例子來說明其應用。
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)) != string::npos){
strBig.replace(pos, srclen, strdst);
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?
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) {
string::size_type pos=0;
string::size_type srclen=strsrc.size();
string::size_type dstlen=strdst.size();
while( (pos=strBig.find(strsrc, pos)) != string::npos){
strBig.erase(pos, srclen);
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)
const charT* c_str() const
const charT* data() const
size_type copy(charT* buf, size_type n, size_type pos = 0) const
你或許會問,c_str()的功能包含data(),那還需要data()函數干什么?看看源碼:
const charT* c_str () const
{ if (length () == 0) return ""; terminate (); return data (); }
string strinfo("this is Winter");
...
//最好的方式是:
foo(strinfo.c_str());
//也可以這么用:
const char* pstr=strinfo.c_str();
foo(pstr);
//不要再使用了pstr了, 下面的操作已經使pstr無效了。
strinfo += " Hello!";
foo(pstr);//錯誤!
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
{
//...
}
想看看實際的例子,你可以看看sgi STL的char_traits結構源碼.
表達式
描述
char_type
字符類型
int_type
int 類型
pos_type
位置類型
off_type
表示位置之間距離的類型
state_type
表示狀態的類型
assign(c1,c2)
把字符c2賦值給c1
eq(c1,c2)
判斷c1,c2 是否相等
lt(c1,c2)
判斷c1是否小于c2
length(str)
判斷str的長度
compare(s1,s2,n)
比較s1和s2的前n個字符
copy(s1,s2, n)
把s2的前n個字符拷貝到s1中
move(s1,s2, n)
把s2中的前n個字符移動到s1中
assign(s,n,c)
把s中的前n個字符賦值為c
find(s,n,c)
在s的前n個字符內查找c
eof()
返回end-of-file
to_int_type(c)
將c轉換成int_type
to_char_type(i)
將i轉換成char_type
not_eof(i)
判斷i是否為EOF
eq_int_type(i1,i2)
判斷i1和i2是否相等
這些都是常用的功能,如果你有興趣可以試試。其實有人已經實現了,看看Extended STL string。如果你想偷懶,下載一個頭文件就可以用,有了它確實方便了很多。要是有人能提供一個支持正則表達式的string,我會非常樂意用。
4 string 建議
使用string 的方便性就不用再說了,這里要重點強調的是string的安全性。
5 小結
難怪有人說:
string 使用方便功能強,我們一直用它!
6 附錄
string 函數列表
函數名
描述
begin
得到指向字符串開頭的Iterator
end
得到指向字符串結尾的Iterator
rbegin
得到指向反向字符串開頭的Iterator
rend
得到指向反向字符串結尾的Iterator
size
得到字符串的大小
length
和size函數功能相同
max_size
字符串可能的最大大小
capacity
在不重新分配內存的情況下,字符串可能的大小
empty
判斷是否為空
operator[]
取第幾個元素,相當于數組
c_str
取得C風格的const char* 字符串
data
取得字符串內容地址
operator=
賦值操作符
reserve
預留空間
swap
交換函數
insert
插入字符
append
追加字符
push_back
追加字符
operator+=
+= 操作符
erase
刪除字符串
clear
清空字符容器中所有內容
resize
重新分配空間
assign
和賦值操作符一樣
replace
替代
copy
字符串到空間
find
查找
rfind
反向查找
find_first_of
查找包含子串中的任何字符,返回第一個位置
find_first_not_of
查找不包含子串中的任何字符,返回第一個位置
find_last_of
查找包含子串中的任何字符,返回最后一個位置
find_last_not_of
查找不包含子串中的任何字符,返回最后一個位置
substr
得到字串
compare
比較字符串
operator+
字符串鏈接
operator==
判斷是否相等
operator!=
判斷是否不等于
operator<
判斷是否小于
operator>>
從輸入流中讀入字符串
operator<<
字符串寫入輸出流
getline
從輸入流中讀入一行
7 參考文章