OneBite.Dev - Coding blog in a bite size

Replace A Substring Within A String In C++

Code snippet for how to Replace A Substring Within A String In C++ with sample and detail explanation

Manipulating text is a common operation in many software applications, and C++ provides a plethora of string functions for this purpose. One common task is replacing a substring within a string. In this article, we will discuss the method for replacing a substring within a string in C++.

Code Snippet: Replace a Substring within a String in C++

C++ provides the string::replace function that allows us to replace a substring with another string. Here is a sample code snippet that demonstrates this:

#include <string>
#include <iostream>

int main() {
    std::string original = "Hello, World!";

    std::size_t found = original.find("World");

    if (found != std::string::npos) {
        original.replace(found, 5, "C++");
    }

    std::cout << original << std::endl;
    return 0;
}

This code will output:

Hello, C++!

Code Explanation: Replace a Substring within a String in C++

Let’s break down the code from the snippet above:

  1. After including the necessary header files, we define the variable original to be our original string: “Hello, World!“.

  2. Then, we use the std::string::find function to find the position of the substring “World”. This function returns the position of the first character of the substring if found, and std::string::npos otherwise.

  3. We then use an if statement to check if the returned value is not std::string::npos (i.e., the substring has been found). If it is found, we proceed to replace it.

  4. To replace the substring, we use the std::string::replace function. It takes three arguments: the position from which to start replacing, the number of characters to replace, and the string to replace with. Here, we replace the five characters starting at the position where “World” was found with “C++“.

  5. Finally, we output the modified string using std::cout.

Please note, the std::string::replace function directly modifies the original string. If you wish to keep the original string unchanged, consider copying the string to a new variable before performing the replacement operation.

c-plus-plus