Home > Mobile >  Replacing even digits in string with given string
Replacing even digits in string with given string

Time:08-13

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 built 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?

CodePudding user response:

You can use constexpr basic_string& basic_string::replace( size_type pos, size_type count, const basic_string& str ); 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;
}
  •  Tags:  
  • c
  • Related