18-替换方法
F.7.5 替换方法
各种replace()方法都指定了要替换的字符串部分和用于替换的内容。可以使用初始位置和字符数目或迭代器区间来指定要替换的部分。替换内容可以是string对象、字符串数组,也可以是特定字符的多个实例。对于用于替换的string对象和数组,可以通过指定特定部分(使用位置和计数或只使用计数)或迭代器区间做进一步的修改。下面是各种replace()方法的原型:
basic_string& replace(size_type pos1, size_type n1, const basic_string& str);
basic_string& replace(size_type pos1, size_type n1, const basic_string& str,
size_type pos2, size_type n2);
basic_string& replace(size_type pos, size_type n1, const charT* s,
size_type n2);
basic_string& replace(size_type pos, size_type n1, const charT* s);
basic_string& replace(size_type pos, size_type n1, size_type n2, charT c);
basic_string& replace(const_iterator i1, const_iterator i2,
const basic_string& str);
basic_string& replace(const_iterator i1, const_iterator i2,
const charT* s, size_type n);
basic_string& replace(const_iterator i1, const_iterator i2,
const charT* s);
basic_string& replace(const_iterator i1, const_iterator i2,
size_type n, charT c);
template<class InputIterator>
basic_string& replace(const_iterator i1, const_iterator i2,
InputIterator j1, InputIterator j2);
basic_string& replace(const_iteraor i1, const_iteator i2,
initializer)list<charT> il);
下面是一个例子:
string test("Take a right turn at Main Street.");
test.replace(7,5,"left"); // replace right with left
注意,您可以使用find()来找出要在replace()中使用的位置:
string s1 = "old";
string s2 = "mature";
string s3 = "The old man and the sea";
string::size_type pos = s3.find(s1);
if (pos != string::npos)
s3.replace(pos, s1.size(), s2);
上述代码将old替换为mature。