-
-
Save dimavs/953183 to your computer and use it in GitHub Desktop.
reverse and replace in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <algorithm> | |
unsigned int reverse_and_replace(std::string& str) | |
{ | |
// reverse string | |
std::reverse(str.begin(), str.end()); | |
// replace all '\' chars and count number of replaces | |
// I am using anonymous functions to do it, so | |
// it should be compiled with -std=c++0x parameter | |
// Technically, it can be done with external function or | |
// function object (functor), but I just like anonymous | |
// functions in a new standard | |
unsigned int count = 0; | |
std::replace_if(str.begin(), str.end(), [&count](char ch) { | |
bool ret = false; | |
if (ch == '\\') | |
{ | |
count++; | |
ret = true; | |
} | |
return ret; | |
// there is a more beautiful way, but I don't think it's readable | |
// return ((ch == '\\') ? ++count, true : false); | |
}, '/'); | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment