C++ replace() 函數用法詳解__Jquery

來源:互聯網
上載者:User

本文主要針對c++中常用replace函數用法給出範例程式

[cpp]  view plain  copy /*用法一:   *用str替換指定字串從起始位置pos開始長度為len的字元   *string& replace (size_t pos, size_t len, const string& str);   */   int main()   {       string line = "this@ is@ a test string!";       line = line.replace(line.find("@"), 1, ""); //從第一個@位置替換第一個@為空白       cout << line << endl;          return 0;   }   運行結果:

[cpp]  view plain  copy /*用法二:   *用str替換 迭代器起始位置 和 結束位置 的字元   *string& replace (const_iterator i1, const_iterator i2, const string& str);   */   int main()   {       string line = "this@ is@ a test string!";       line = line.replace(line.begin(), line.begin()+6, "");  //用str替換從begin位置開始的6個字元       cout << line << endl;          return 0;   }   運行結果:


[cpp]  view plain  copy /*用法三:   *用substr的指定子串(給定起始位置和長度)替換從指定位置上的字串   *string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);   */   int main()   {       string line = "this@ is@ a test string!";       string substr = "12345";       line = line.replace(0, 5, substr, substr.find("1"), 3); //用substr的指定子串(從1位置數共3個字元)替換從0到5位置上的line       cout << line << endl;          return 0;   }   運行結果:

[cpp]  view plain  copy /*用法四:string轉char*時編譯器可能會報出警告,不建議這樣做   *用str替換從指定位置0開始長度為5的字串   *string& replace(size_t pos, size_t len, const char* s);   */   int main()   {       string line = "this@ is@ a test string!";       char* str = "12345";       line = line.replace(0, 5, str); //用str替換從指定位置0開始長度為5的字串       cout << line << endl;     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.