1. 程式人生 > 其它 >c++ string的查詢與替換

c++ string的查詢與替換

功能描述:
查詢:查詢指定字串是否存在
替換:在指定的位置替換字串
函式原型:
int find(const string& str, int pos = 0) const; //查詢str第一次出現位置,pos開始查詢
int find(const char* s, int pos = 0) const; //查詢s第一次出現位置,pos開始查詢
int find(const char* s, int pos, int n) const; //pos位置查詢s的前n個字元第一次位置
int find(const char c, int pos = 0) const; //查詢字元c第一次出現位置
int rfind(const string& str, int pos = npos) const; //查詢str最後一次位置,pos開始查詢
int rfind(const char* s, int pos = npos) const; //查詢s最後一次出現位置,pos開始查詢
int rfind(const char* s, int pos, int n) const; //pos查詢s的前n個字元最後一次位置
int rfind(const char c, int pos = 0) const; //查詢字元c最後一次出現位置
string& replace(int pos, int n, const string& str); //替換從pos開始n個字元為字串str
string& replace(int pos, int n,const char* s); //替換從pos開始的n個字元為字串s

注意,rfind是從左往右找,同時pos位置指的是從左往右忽略到第幾個位置,但是最終得到的結果是正常從右往左的序列結果,比如rfind(“a”,0)最後得到的結果一定是0或者-1,因為其他位置的都被忽略掉了。另一方面,注意replace的時候,替換的數量是輸入的,但是實際插入的結果受實際輸入制約,比如替換3個,但是輸入了四個,結果也是替換掉了三個,但是插入了四個

  string s1 = "abcdefgaaa";   int pos = s1.find("d1",0);   cout << pos <<endl;   int poe = s1.rfind("de",7);
  cout << poe <<endl;   s1.replace(1,3,"11111");   cout << s1 <<endl;   s1.replace(6,3,"1");   cout << s1 <<endl;   -1
3
a11111efgaaa
a111111aaa