Home C++ Strings Functions replace() C++ std::string replace() Function Definition In C++, std::string::replace() removes a slice of characters and inserts new text in that place.
Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax Index form is common:
s.replace(pos, len, newText);
s.replace(pos, len, n, ch); Call What it does s.replace(pos, len, str)Replace len chars at pos with str. s.replace(pos, len, n, ch)Replace that slice with n copies of ch.
If pos > size(), throws std::out_of_range. If len is large, it replaces through the end.
Library declarations string& replace(size_type pos, size_type len, const string& str);
string& replace(size_type pos, size_type len, size_type n, char c); Parameters Parameter Description pos, lenSlice to remove. replacement String, C-string, or repeated character.
Return Value Return Value Description string&Reference to *this.
C++ Examples 1. Replace word 2. Replace with fill 3. Longer replacement Example 1 — Basic replace() Replace a middle word.
#include <iostream>
#include <string>
int main() {
std::string s = "I like Java";
s.replace(7, 4, "C++");
std::cout << s << '\n';
return 0;
} How It Works Index 7 length 4 selects "Java". It is replaced with "C++". Surrounding text stays. Example 2 — Replace With Stars Mask part of a string.
#include <iostream>
#include <string>
int main() {
std::string s = "secret";
s.replace(0, 3, 3, '*');
std::cout << s << '\n';
return 0;
} How It Works First three letters are removed. Three stars are inserted. Suffix "ret" remains. Example 3 — Replacement Can Grow New text can be longer than the slice.
#include <iostream>
#include <string>
int main() {
std::string s = "aXb";
s.replace(1, 1, "YYY");
std::cout << s << '\\n';
std::cout << s.size() << '\\n';
return 0;
} How It Works One character 'X' is removed. Three Ys take its place. Size grows from 3 to 5. Frequently Asked Questions What does replace do? It removes a slice and inserts new characters there.
Can the new text be longer? Yes. The string grows or shrinks as needed.
What if pos is invalid? Throws std::out_of_range when pos > size().
How do I replace the whole string? Use assign or operator=; or replace(0, s.size(), newText).
What is replace_with_range? C++23 overload that inserts a range as the replacement.
CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful
Helpful Share Copy link Suggestion