Search⌘ K
AI Features

Modifying Strings: Inserting, Deleting, and Replacing Characters

Understand how to modify strings in C++ by using insert, erase, and replace operations on std::string. Learn how to efficiently insert characters or substrings at specific positions, delete unwanted characters or ranges, and replace characters or substrings. Explore the time and space complexity involved, and how to utilize in-place modifications effectively in string algorithms.

By now, you understand that std::string in C++ is mutable and that its contents can be changed in place. That raises a practical question: how do you perform the kinds of modifications that real programs and algorithms constantly require? Inserting a character at a specific position, removing an unwanted character, and replacing one substring with another are fundamental operations. Understanding how to perform them correctly and efficiently is what we will cover now.

Inserting a character

Inserting a character at a specific position means placing a new character at a given index and shifting every character from that position onward one step to the right to accommodate it.

Consider the string "helo" and the requirement to insert the character 'l' at index 3.

Before: h e l o
Index: 0 1 2 3
After: h e l l o
Index: 0 1 2 3 4

The character o that was at index 3 has moved to index 4 to make room for the inserted character. In general, inserting at position i requires shifting every character from index i to the end of the string one position to the right. In the worst case, inserting at the beginning of the string requires shifting all n existing characters, making insertion an O(n) operation.

Using the insert() member function

C++ provides the insert() member function on std::string, which inserts characters at a specified ...