OneBite.Dev - Coding blog in a bite size

Replace A Word In A String In C++

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

Manipulating strings is a fundamental skill when working in any programming language. In C++, replacing a word within a string might seem like a daunting task, but with the use of the right function and syntax, it’s quite straightforward.

Code snippet: Replacing a Word in a String in C++

Let’s take a look at a simple code snippet which demonstrates how to replace a word in a string.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string str = "Hello World!";
    string word_to_replace = "World";
    string new_word = "C++";

    size_t pos = str.find(word_to_replace);
    if (pos != string::npos)
    {
        str.replace(pos, word_to_replace.length(), new_word);
    }

    cout << str << endl;

    return 0;
}

When you run the code, the output will be “Hello C++!“.

Code Explanation: Replacing a Word in a String in C++

Let’s break down each part of the code.

Our example demonstrates replacing a word in a string. We start with a string that says “Hello World!“. We are going to replace “World” with “C++“.

We begin by including the necessary libraries.

#include <iostream>
#include <string>
#include <algorithm>

We’re using the standard namespace std, so we don’t have to prepend std:: every time we use a function from the standard library.

using namespace std;

Next, we define our main function, the entry point of the program.

int main() {

We define a string, str, and two additional strings, word_to_replace and new_word.

string str = "Hello World!";
string word_to_replace = "World";
string new_word = "C++";

Then we find the position of the word to replace in the original string using the find() function. If the word is found within the string, find() returns the position of the first character of the found substring; if not, it returns string::npos.

size_t pos = str.find(word_to_replace);

An if-statement checks whether word_to_replace is found in the string. If found, replace it with new_word using the replace() function.

if (pos != string::npos)
{
    str.replace(pos, word_to_replace.length(), new_word);
}

Finally, we print out the modified string, which should now say, “Hello C++!“.

cout << str << endl;

That concludes our demonstration of replacing a word in a string in C++. As you can see, with the right functions and proper use, manipulating strings in C++ can be straightforward.

c-plus-plus