1. 程式人生 > >標準庫string總結2

標準庫string總結2

sbustr操作

string substr(int pos=0, int n=npos) const;    //返回由pos開始的n個字元組成的子字串
string s("Hello World");
string s1=s.substr(0,5); //s1=Hello
string s2=s.substr(6); //s2=World
string s3=s.substr(6,11); //s3 = World
string s4=s.substr(12); //丟擲一個異常out_of_range

compare函式

int compare(const string &
s) const; //與字串s比較 int compare(const char *s) const; //與字串s比較
string s1("hello");
string s2("Hello");
s1.compare(s2);
//當s1大於s2時,返回一個等於零的數;
//當s1等於s2時,返回0;
//當s1小於s2時,返回一個小於零的數;
//比較時參考字典順序,排越前面的越小。大寫的A比小寫的a小。
//通過測試得到,其實返回值是兩個字串所對應第一對不同字元的ASCII碼的差值

string查詢函式

s.find(args); //查詢s中args第一次出現的位置
s.rfind(args)
; //反向查詢,查詢s中args最後一次出現的位置 s.find_first_of(args); //在s中查詢args中任何一個字元第一次出現的位置 s.find_last_of(args); //在s中查詢args中任何一個字元最後一次出現的位置 s.find_first_not_of(args); //在s中查詢第一個不在args中的字元 s.find_last_not_of(args); //在s中查詢最後一個不在args中的字元

返回值:
每個搜尋返回一個string::size_type值,表示匹配發生位置的下標;如果搜尋失敗,則返回一個名為string::npos,其值為-1。

  • string搜尋函式返回string::size_type值,該型別是一個unsigned型別。所以用int表示返回值,其實並不滿意。

string查詢還可以指定某個位置起查詢:

int find(char c,int pos=0) const;  //從pos開始查詢字元c在當前字串的位置 
int find(const char *s, int pos=0) const;  //從pos開始查詢字串s在當前字串的位置
int find(const string &s, int pos=0) const;  //從pos開始查詢字串s在當前字串中的位置
//find函式如果查詢不到,就返回npos
int rfind(char c, int pos=npos) const;   //從pos開始從後向前查詢字元c在當前字串中的位置 
int rfind(const char *s, int pos=npos) const;
int rfind(const string &s, int pos=npos) const;
//rfind是反向查詢的意思,如果查詢不到, 返回npos

string替換函式

string &replace(int pos, int n, const char *s);//刪除從pos開始的n個字元,然後在pos處插入串s
string &replace(int pos, int n, const string &s);  //刪除從pos開始的n個字元,然後在pos處插入串s

replace()函式在替換字元或字串時,不必與要替換的字串的長度相同,可以長也可以短。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s="you are good,you are happy!";
    auto k=s.find("you");
    while(k!=string::npos)
    {
        s.replace(k,3,"we");
        k=s.find("you",k);
    }
    //替換後輸出
    cout<<s<<endl; //we are good,we are happy!
    return 0;
}

string區間刪除與插入

string &insert(int pos, const char *s);
string &insert(int pos, const string &s);
//前兩個函式在pos位置插入字串s
string &insert(int pos, int n, char c);  //在pos位置 插入n個字元c

string &erase(int pos=0, int n=npos);  //刪除pos開始的n個字元,返回修改後的字串