OneBite.Dev - Coding blog in a bite size

Replace Multiple Words In A String In C++

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

In the realm of programming, oftentimes, there arises a need to replace certain words in a string. This article specifically dives into the aspect of replacing multiple words in a string by using C++. This is not a complex process but a necessary one for many programming scenarios.

Code snippet for Replacing Multiple Words in a String

Firstly, let’s take a look at a simple code snippet that performs this task:

// Including necessary header file
#include<iostream>
#include<string>

void replace_words(std::string& str, const std::string& old_word, const std::string& new_word)
{
    size_t pos = 0;

    while((pos = str.find(old_word, pos)) != std::string::npos) 
    {
        str.replace(pos, old_word.length(), new_word);
        pos += new_word.length(); 
    }
}

int main() 
{
    std::string str = "Hello world, welcome to the world of programming!";

    replace_words(str, "world", "universe");
  
    std::cout << "Modified string: " << str;

    return 0;
}

Code Explanation for Replacing Multiple Words in a String

The code provided above is quite straightforward and easy to understand. It includes a function replace_words, which replaces the occurrences of an old word (old_word) with a new word (new_word) in a given string (str).

The program starts with including necessary headers - iostream for standard input/output streams and string for manipulating strings.

In the replace_words function, we define an unsigned int type, ‘pos’, to store the position of old_word in str. We use a loop to find all occurrences of old_word in str, starting from the previously found position (initially 0).

The find function tries to find the ‘old_word’ in str after the ‘pos’ position. If it finds it, it returns the starting position of the ‘old_word’. If it doesn’t find it, it returns a constant ‘std::string::npos’.

When occurrences are found, the replace function is used to replace the old_word with the new_word starting from the found position (pos). The length of old_word is used to determine how much string should be replaced. After each replacement, pos is increased by the length of new_word so the next search can start after the newly inserted word.

In the main function, we initialize the string and call the replace_words function to replace “world” with “universe”. The output is printed to display the modified string.

And that’s it, this way, we can successfully replace multiple word occurrences in a string with C++.

c-plus-plus