Skip to content

Instantly share code, notes, and snippets.

@dimavs
Created May 3, 2011 11:19
Show Gist options
  • Save dimavs/953183 to your computer and use it in GitHub Desktop.
Save dimavs/953183 to your computer and use it in GitHub Desktop.
reverse and replace in c++
#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