PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

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

 November 03, 2022     c++, lambda, replace, string     No comments   

Issue

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



Answered By - Miles Budnek
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing