Modifying Operations
C++ gives us a variety of tools to modify and manipulate strings.
Strings have many operations to modify them. str.assign
assigns a new string to the string str
. With str.swap
you can swap two strings. To remove a character from a string use str.pop_back
or str.erase
. In contrary str.clear
or str.erase
deletes the whole string. To append new characters to a string use +=, std.append
or str.push_back
. You can use str.insert
to insert new characters or str.replace
to replace characters.
The following are the methods for modifying a string:
Methods | Description |
---|---|
str= str2 |
Assigns str2 to str . |
str.assign(...) |
Assigns to str a new string. |
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 are available in many overloaded versions. The methods str.assign
, str.append
, str.insert
and str.replace
are very similar. All four can be invoked with C+±strings and substrings, but also characters, C strings, C string arrays, ranges, and initializer lists. str.erase
can erase a single character, ranges, but also many characters starting at a given position.
The following code snippets show many of the variations. For simplicity reasons only the effects of the strings modifications are displayed:
Get hands-on with 1400+ tech skills courses.