Replacing even digits in string with given string

Viewed 75

I know how to replace all occurrences of a character with another character in string (How to replace all occurrences of a character in string?)

But what if I want to replace all even numbers in string with given string? I am confused between replace, replace_if and member replace/find functions of basic_string class, because signature of functions require old_val and new_val to be same type. But old_val is char, and new_val is string. Is there any effective way to do this, not using multiple loops?

e.g. if the input string is

"asjkdn3vhsjdvcn2asjnbd2vd"

and the replacement text is

"whatever"

, the result should be

"asjkdn3vhsjdvcnwhateverasjnbdwhatevervd"

2 Answers

You can use std::string::replace() to replace a character with a string. A working example is below:

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

void replace_even_with_string(std::string &inout)
{
    auto is_even = [](char ch)
    {
        return std::isdigit(static_cast<unsigned char>(ch)) && ((ch - '0') % 2) == 0;
    };
    std::string_view replacement_str = "whatever";
    auto top = std::find_if(inout.begin(), inout.end(), is_even) - inout.begin();
    for (std::string::size_type pos{};
         (pos = (std::find_if(inout.begin() + pos, inout.end(), is_even) - inout.begin())) < inout.length();
         pos += replacement_str.length() - 1)
    {
        inout.replace(pos, 1, replacement_str.data());
    }
}

int main()
{
    std::string test = "asjkdn3vhsjdvcn2asjnbd2vd";
    std::cout << test << std::endl;
    replace_even_with_string(test);
    std::cout << test << std::endl;
}

While using a regex can add unnecessary complexity in many cases, here it's actually simple to read and write:

std::string str = /* ... some text ... */
std::regex r{R"~~([02468])~~"};           // this will match even digits
str = std::regex_replace(str, r, "rep");  // replace with the needed text 
                                          // and overwrite string

Here's a demo.

Related