Replace all occurrences of a character in String in C++

In this article, we will discuss different ways to replace all occurrences of a character from a string with an another character in C++.

Table Of Contents

Suppose we have a string,

"Some extra text"

We want to replace all the occurrence of character ‘e’ with ‘P’ in this string. After that, the final string should be like,

"SomP Pxtra tPxt"

There are different ways to this. Let’s discuss them one by one.

Using STL Algorithm std::replace()

In C++, the STL provides a function to replace() to change the contents of an iterable container. As string is a collection of characters, so we can use the std::replace() function to replace all the occurrences of character ‘e’ with character ‘P’ in the string. For this, we need to pass the following arguments to the std::replace() function,

  • Iterator pointing to the start of string.
  • Iterator pointing to the end of string.
  • Character to be replaced i.e. ‘e’.
  • Replacement character i.e. ‘P’.

It will replace all occurrences of character ‘e’ with the characyter ‘P’ in the string.

For example,

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

int main()
{
    std::string strValue = "Some extra text";

    const char toBeReplaced = 'e';
    const char replacement  = 'P';

    // Replace all occurrences of character 'e' with 'P'
    std::replace(strValue.begin(),
                 strValue.end(),
                 toBeReplaced,
                 replacement);

    std::cout<< strValue << std::endl;
}

Output:

SomP Pxtra tPxt

It replaced all occurrences of character ‘e’ in the string with the the character ‘P’.

Using string::replace() and find()

We can look for the index positions of given character in the string using find() function and replace them using the string::replace() function.

Steps are as follows,

  • Find the Index position of given character in the string using string::find() function.
  • While the index position is valid,
    • Replace the character at that index position with the replacement character using std::replace()
    • Again find the index position of given character in the string using string::find() function.

Let’s understand this with an example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue = "Some extra text";

    const char toBeReplaced = 'e';
    const char replacement  = 'P';

    size_t pos = strValue.find(toBeReplaced);

    // Replace all occurrences of character 'e' with 'P'
    while( pos != std::string::npos)
    {
        strValue.replace(pos, 1, 1, replacement);
        pos = strValue.find(toBeReplaced);
    }

    std::cout<< strValue << std::endl;
}

Output:

SomP Pxtra tPxt

We looked for all the index positions of character ‘e’ in the string using find(). Then we replaced the characters at those index positions with the character ‘P’ using the string::replace() function. For replacing a character at a time using the string::replace() function, we need to pass following arguments,

  • Index position in string from where it needs to start the replacement.
  • Number of characters that need to be replaced. In our case it was 1.
  • Number of characters to copy. In our case it was 1.
  • Character value, that will be repeated n times. In our case it was ‘P’.

It replaced all the occurrences of character ‘e’ with the ‘P’ in the string.

Using Iteration

What if we have a char array instead of string?

Iterate over all the characters in the char array and for each character check if it is equal to the character that need to replaced. If yes, then replace the value at that index position in string / char array with the replacement character.

For example,

#include <iostream>

int main()
{
    char strValue[] = "Some extra text";

    const char toBeReplaced = 'e';
    const char replacement  = 'P';

    size_t len = sizeof(strValue) / sizeof(strValue[0]);

    // Iterate over all characters in the char array
    for (int i = 0; i < len; i++)
    {
        // Check if character needs to be replaced
        if (strValue[i] == toBeReplaced)
        {
            // Replace the character
            strValue[i] = replacement;
        }
    }

    std::cout<< strValue << std::endl;
}

Output:

SomP Pxtra tPxt

We replaced all the occurrences of the character ‘e’ with ‘P’ in the string.

Summary:

We learned about three different ways to replace all occurrences of a character in a string in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top