3

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"

cigien
  • 57,834
  • 11
  • 73
  • 112
Almaz
  • 33
  • 5
  • You're interpreting the *content* of the string as something it natively isn't : *numbers*. That interpretation requires additional work, be it in the form of added loops, usage of library algorithms or stream assists, etc. There is no magic silver bullet to just fire that is does for you. That said, if by "numbers" you *really* mean *digit characters* it makes a big difference, as you can mostly return to the roots of replace_if since you're back in character-land. – WhozCraig Aug 13 '22 at 11:06
  • @WhozCraig yeah, my bad. i mean digit characters 0..9 – Almaz Aug 13 '22 at 11:35

2 Answers2

2

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

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.

cigien
  • 57,834
  • 11
  • 73
  • 112