Search code examples
c++stringlambdareplace

How to use std::replace_if to replace elements with its incremented value?


I am trying to write a std::replace_if function that takes in a string and replaces all the vowels with a consonant on its right.

How to capture the current iterating character from the string and replace it with its incremented value using a lambda within std::replace_if function

Example :

input : aeiou

output : bfjpv

Assume all characters to be lowercase

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

int main()
{
    std::string str;
    std::cin >> str;

    std::replace_if(
        str.begin(), str.end(), [&](char c)
        { return std::string("aeiou").find(c) != std::string::npos; },
        [&](char c)
        { return static_cast<char>(c + 1); });

    std::cout << str;
}


Solution

  • std::replace_if cannot do what you want. It accepts only a single new value.

    To do what you want either use std::for_each:

    std::for_each(
        str.begin(),
        str.end(),
        [](char& c) {
            if (std::string("aeiou").find(c) != std::string::npos) {
                c = c + 1;
            }
        }
    );
    

    Demo

    Or use a normal loop:

    for (char& c : str) {
        if (std::string("aeiou").find(c) != std::string::npos) {
            c = c + 1;
        }
    }
    

    Demo