String modification
- C++ course
- Beginner
- Lesson 92/116
- 5 min
Learn string modification with .replace() and .insert().
Replacing parts with replace
The .replace() method of the string class replaces a part of the string starting at a given position with another string. The first parameter is the start position, the second is the number of characters to remove, and the third is the replacement string.
string s = "hello world";
s.replace(6, 5, "c++"); // "hello c++"Here, starting at position 6, 5 characters ("world") are removed and "c++" is put in their place. Positions are zero-based; s[0] is the first character. You can learn the string length with the .size() method.
Inserting with insert
The .insert() method inserts a string at a given position; existing characters shift to the right. The first parameter is the position, the second is the string to insert.
string s = "hello";
s.insert(0, "hi "); // "hi hello"Here "hi " is inserted at position 0; the original "hello" shifts right. With insert you can place new pieces at the start, middle, or end of a string; the string grows automatically.
Practice Replace a part with replace
Define string s = "hello world";. Use s.replace(6, 5, "c++"); to remove 5 characters at position 6 and put "c++" in their place. Then print it with cout << s << endl;.
Starter code
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
// use replace to swap 5 characters at position 6 with "c++", then print
return 0;
}Sample solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "hello world";
s.replace(6, 5, "c++");
cout << s << endl;
return 0;
}Expected output
hello c++
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: replace call
string s = "green leaf";
s.____(6, 5, "bird");
string s = "green leaf";
s.replace(6, 5, "bird");
Explanation: replace swaps a part of the string.
2 What does s.insert(0, "x") do?
- Inserts "x" at the start of s Correct answer
- Appends "x" to the end of s
- Removes the first character of s
- Replaces s with "x"
Explanation: Position 0 means the start; "x" is added at the beginning.
3 Match each method with its job
| Term | Meaning |
|---|---|
replace |
Swaps a part |
insert |
Inserts in the middle |
size |
Returns length |