淺談C++中replace()辦法。本站提示廣大學習愛好者:(淺談C++中replace()辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是淺談C++中replace()辦法正文
本文重要針對c++中經常使用replace函數用法給出九個樣例法式:
用法一:
/*
*用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;
}
運轉成果:
用法二:
/*
*用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;
}
運轉成果:
用法三:
/*
*用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;
}
運轉成果:
用法四: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;
return 0;
}
運轉成果:
用法五:string轉char*時編譯器能夠會報出正告,不建議如許做
/*
*用str調換從指定迭代器地位的字符串
*string& replace (const_iterator i1, const_iterator i2, const char* s);
*/
int main()
{
string line = "this@ is@ a test string!";
char* str = "12345";
line = line.replace(line.begin(), line.begin()+9, str); //用str調換從指定迭代器地位的字符串
cout << line << endl;
return 0;
}
運轉成果:
用法六:string轉char*時編譯器能夠會報出正告,不建議如許做
/*
*用s的前n個字符調換從開端地位pos長度為len的字符串
*string& replace(size_t pos, size_t len, const char* s, size_t n);
*/
int main()
{
string line = "this@ is@ a test string!";
char* str = "12345";
line = line.replace(0, 9, str, 4); //用str的前4個字符調換從0地位開端長度為9的字符串
cout << line << endl;
return 0;
}
運轉成果:
用法七:string轉char*時編譯器能夠會報出正告,不建議如許做
/*
*用s的前n個字符調換指定迭代器地位(從i1到i2)的字符串
*string& replace (const_iterator i1, const_iterator i2, const char* s, size_t n);
*/
int main()
{
string line = "this@ is@ a test string!";
char* str = "12345";
line = line.replace(line.begin(), line.begin()+9, str, 4); //用str的前4個字符調換指定迭代器地位的字符串
cout << line << endl;
return 0;
}
運轉成果:
用法八:
/*
*用反復n次的c字符調換從指定地位pos長度為len的內容
*string& replace (size_t pos, size_t len, size_t n, char c);
*/
int main()
{
string line = "this@ is@ a test string!";
char c = '1';
line = line.replace(0, 9, 3, c); //用反復3次的c字符調換從指定地位0長度為9的內容
cout << line << endl;
return 0;
}
運轉成果:
用法九:
/*
*用反復n次的c字符調換從指定迭代器地位(從i1開端到停止)的內容
*string& replace (const_iterator i1, const_iterator i2, size_t n, char c);
*/
int main()
{
string line = "this@ is@ a test string!";
char c = '1';
line = line.replace(line.begin(), line.begin()+9, 3, c); //用反復3次的c字符調換從指定迭代器地位的內容
cout << line << endl;
return 0;
}
運轉成果:
注:一切應用迭代器類型的參數不限於string類型,可認為vector、list等其他類型迭代器。