1. 程式人生 > >string 的一些字串操作函式

string 的一些字串操作函式

1.find查詢函式
函式原型:

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

引數說明:pos查詢起始位置 n待查詢字串的前n個字元

find函式在找不到指定值得情況下會返回string::npos

使用樣例:

string str1("the usage of find can you use it");

string str2("the");

上面定義出了兩個字串;

str1.find(str2); // 從串str1中查詢時str2,返回str2中首個字元在str1中的地址

str1.find(str2,5); // 從str1的第5個字元開始查詢str2,成功返回str2的首字母的下標位置

str1.find("usage"); // 如果usage在str1中查詢到,返回u在str1中的位置

str1.find("o"); // 查詢字元o並返回地址

str1.find("of big",2,2); // 從str1中的第二個字元開始查詢of big的前兩個字元
2.函式find_first_of()和 find_last_of() 執行簡單的模式匹配
int find_first_of(char c, int start = 0):
查詢字串中第1個出現的c,由位置start開始。
如果有匹配,則返回匹配位置;否則,返回-1.預設情況下,start為0,函式搜尋
整個字串。
int find_last_of(char c,int end):


查詢字串中最後一個出現的c。有匹配,則返回匹配位置;否則返回-1.
該搜尋在字元末尾查詢匹配,所以沒有提供起始位置。
同樣還可以有find_first_not_of等函式,函式名顧名思義,就是找第一個不是我要求字元的位置,注意,輸出的結果總是下標,下標是從0開始的。
3. string substr(int start=0,int count= -1);
引數分別是開始,長度。
從起始位置開始複製字串中的count 個字元,並返回這些字元作為子串。
如果字串尾部小於count字元或者count 為-1,則字串尾停止複製。
如果不使用引數呼叫只包括位置start,則substr()返回從位置開始到字串尾部的子串。
4.void insert(int statr,const string& s):
字元連線(+、+=)是在字串尾新增字串。insert()函式擴充套件了這個能力,
允許在任意位置新增字串。為了從字串。
將子串s放入字串中,起始於位置start。插入操作增加了原始字串的長度。
string &insert(int p0, const char *s, int n);——在p0位置插入字串s的前n個字元
string &insert(int p0,const string &s);——在p0位置插入字串s
string &insert(int p0,const string &s, int pos, int n);——在p0位置插入字串s從pos開始的連續n個字元
string &insert(int p0, int n, char c);//在p0處插入n個字元c
iterator insert(iterator it, char c);//在it處插入字元c,返回插入後迭代器的位置
void insert(iterator it, const_iterator first, const_iteratorlast);//在it處插入從first開始至last-1的所有字元
void insert(iterator it, int n, char c);//在it處插入n個字元c
5.erase()函式
iterator erase(iterator first, iterator last);//刪除[first,last)之間的所有字元,返回刪除後迭代器的位置
iterator erase(iterator it);//刪除it指向的字元,返回刪除後迭代器的位置
string &erase(int pos = 0, int n = npos);//刪除pos開始的n個字元,返回修改後的字串
6.c_str()返回c語言風格字串的地址。