c++中replace函式用法總結
阿新 • • 發佈:2019-01-27
一、用法一
string& replace (size_t pos, size_t len, const string& str) 用str 替換指定字串從起始位置pos開始長度為len 的字元
replace(i, j, str); 用str 替換從i 開始的長度為 j 的字元
例子:
#include<iostream> using namespace std; int main(){ string line="hello world, i love python!"; string s = line.replace(line.find("i"), 1, "haha"); cout<<s<<endl; return 0; }
輸出
二、用法二
string& replace (const_iterator i1, const_iterator i2, const string& str);
用str替換 迭代器起始位置和結束位置的字元
例子:
#include<iostream> using namespace std; int main(){ string line="hello world, i love python!"; string s = line.replace(line.begin(), line.begin()+5, "haha"); cout<<s<<endl; return 0; }
輸出:
三、用法三
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
用substr 的指定子串(給定起始位置和長度)替換從指定位置上的字串
例子:
#include<iostream> using namespace std; int main(){ string line="hello world, i love python!"; string substr="12345"; string s = line.replace(0, 5, substr, substr.find("2"), 3); cout<<s<<endl; return 0; }
輸出:
四、用法四
string& replace (size_t pos, size_t len, size_t n, char c);
用重複n 次的c 字元替換從指定位置 pos 長度為 len 的內容
例子:
#include<iostream>
using namespace std;
int main(){
string line="hello world, i love python!";
char substr='1';
string s = line.replace(0, 5, 3, substr);
cout<<s<<endl;
return 0;
}
輸出:
五、用法五
string& replace (const_iterator i1, const_iterator i2, size_t n, char c)
用重複 n 次的 c 字元替換從指定迭代器位置(從 i1 開始到結束)的內容
例子:
#include<iostream>
using namespace std;
int main(){
string line="hello world, i love python!";
char substr='1';
string s = line.replace(line.begin(), line.begin()+5, 3, substr);
cout<<s<<endl;
return 0;
}
輸出: