The insert()
methods let you insert a string
object, a string array, a character, or several characters into a string
object. The methods are similar to the append()
methods, except that they take an additional argument, indicating where to insert the new material. This argument may be a position or an iterator. The material is inserted before the insertion point. Several of the methods return a reference to the resulting string. If pos1
is beyond the end of the target string or if pos2
is beyond the end of the string to be inserted, a method throws an out_of_range
exception. If the resulting string will be larger than the maximum size, a method throws a length_error
exception. Here are the prototypes for the various insert()
methods:
basic_string& insert(size_type pos1, const basic_string& str);
basic_string& insert(size_type pos1, const basic_string& str,
size_type pos2, size_type n);
basic_string& insert(size_type pos, const charT* s, size_type n);
basic_string& insert(size_type pos, const charT* s);
basic_string& insert(size_type pos, size_type n, charT c);
iterator insert(const_iterator p, charT c);
iterator insert(const_iterator p, size_type n, charT c);
template<class InputIterator>
void insert(iterator p, InputIterator first, InputIterator last);
iterator insert(const_iterator p, initializer_list<charT>); // C++11
For example, the following code inserts the string "former "
before the b
in "The banker."
:
string st3("The banker.");
st3.insert(4, "former ");
Then the following code inserts the string " waltzed"
(not including the !
, which would be the ninth character) just before the period at the end of "The former banker."
:
st3.insert(st3.size() - 1, " waltzed!", 8);
18.117.229.44