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:
-
After including the necessary header files, we define the variable
original
to be our original string: “Hello, World!“. -
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, andstd::string::npos
otherwise. -
We then use an
if
statement to check if the returned value is notstd::string::npos
(i.e., the substring has been found). If it is found, we proceed to replace it. -
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++“. -
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.