Modifying Strings
The following function allows us to modify the current string.
1. insert()
The insert() function not only allows us to add a string but also allows us to add it at the specified position. It is also a member function of the std::string class.
Syntax
str1.insert(index, str2);
Parameters
- str2: string to be inserted.
- index: position of where to insert the new string
Return Type
- Reference to the str1.
Example
std::string text = "I have a cat."; text.insert(9, " black"); // Insert " black" at position 9
2. replace()
The replace() function replaces the part of the string with the given other string. Unlike insert, the characters in the part where the new string is to be inserted are removed.
Syntax
str1.replace(index, size, str2);
Parameters
- index: Index of where to start replacing the new string.
- size: length of the part of the string that is to be replaced.
- str2: new string that is to be inserted.
Return Type
- Reference to the str1.
Example
std::string text = "I like dogs."; text.replace(7, 4, "cats"); // Replace "dogs" with "cats"
3. erase()
The erase() function is a member function of std::string class that is used to remove a character or a part of the string.
Syntax
str1.erase(start, end);
Parameters
- start: Starting position.
- end: Ending position.
Return Type
- Reference to the str1.
Example
std::string text = "This is an example."; text.erase(5, 3); // Erase "is "
String Functions In C++
A string is referred to as an array of characters. In C++, a stream/sequence of characters is stored in a char array. C++ includes the std::string class that is used to represent strings. It is one of the most fundamental datatypes in C++ and it comes with a huge set of inbuilt functions. In this article, will look at the functions of string computations.
Contact Us