0
0
CppHow-ToBeginner · 3 min read

How to Replace Text in a String in C++

In C++, you can replace part of a string using the std::string::replace method by specifying the start position, length of the part to replace, and the new string. Alternatively, you can use std::regex_replace for pattern-based replacements.
📐

Syntax

The std::string::replace method replaces a portion of the string starting at a given position and spanning a given length with another string.

  • pos: The starting index where replacement begins.
  • len: The number of characters to replace.
  • str: The new string to insert.
cpp
string& replace (size_t pos, size_t len, const string& str);
💻

Example

This example shows how to replace a word inside a string using replace. It replaces "world" with "C++".

cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "Hello world!";
    size_t pos = text.find("world");
    if (pos != std::string::npos) {
        text.replace(pos, 5, "C++");
    }
    std::cout << text << std::endl;
    return 0;
}
Output
Hello C++!
⚠️

Common Pitfalls

Common mistakes include:

  • Not checking if the substring exists before replacing, which can cause unexpected behavior.
  • Using incorrect positions or lengths that go beyond the string size.
  • Confusing replace with replace_all which does not exist in std::string.
cpp
#include <iostream>
#include <string>

int main() {
    std::string text = "Hello world!";
    // Wrong: not checking if "planet" exists
    size_t pos = text.find("planet");
    // This will replace from npos which is invalid
    if (pos != std::string::npos) {
        text.replace(pos, 6, "Earth");
    } else {
        std::cout << "Substring not found, no replacement done." << std::endl;
    }
    std::cout << text << std::endl;
    return 0;
}
Output
Substring not found, no replacement done. Hello world!
📊

Quick Reference

MethodDescriptionExample Usage
std::string::replaceReplace part of string by position and lengthtext.replace(pos, len, "new")
std::string::findFind substring positionpos = text.find("old")
std::regex_replaceReplace using pattern matching (requires )std::regex_replace(text, std::regex("old"), "new")

Key Takeaways

Use std::string::replace with position and length to replace parts of a string.
Always check if the substring exists using find() before replacing.
Avoid out-of-range positions to prevent runtime errors.
For pattern-based replacements, use std::regex_replace from .
std::string::replace replaces only one part; loop or regex needed for multiple replacements.