Modifying Operations
C++ gives us a variety of tools to modify and manipulate strings.
Strings have many operations that can modify them. str.assign
assigns a new string to the string str
. With str.swap
we can swap two strings. To remove a character from a string use str.pop_back
or str.erase
. On the contrary, str.clear
or str.erase
deletes the whole string. To append new characters to a string, use +=, std.append
or str.push_back
. We can use str.insert
to insert new characters or str.replace
to replace them.
Methods | Description |
---|---|
str= str2 |
Assigns str2 to str . |
str.assign(...) |
Assigns a new string to str . |
str.swap(str2) |
Swaps str and str2 . |
str.pop_back() |
Removes the last character from str . |
str.erase(...) |
Removes characters from str . |
str.clear() |
Clears the str . |
str.append(...) |
Appends characters to str . |
str.push_back(s) |
Appends the character s to str . |
str.insert(pos, ...) |
Inserts characters in str starting at pos . |
str.replace(pos, len, ...) |
Replaces the len characters from str starting at pos |
Methods for modifying a string
The operations have many overloaded versions. The methods str.assign
, str.append
, str.insert
, and str.replace
are very similar. All four can not only be invoked with C++ strings and substrings but also characters, C strings, C string arrays, ranges, and initializer lists. str.erase
can not only erase a single character and whole ranges, but also many characters starting at a given position.
The following code snippet shows many of the variations. For the sake of simplicity, only the effects of the strings modifications are displayed: