sexta-feira, 17 de agosto de 2012

Replace all occurrences of a character in a std::string with another character


in one line of C++ code, using C++11/C++0x:

std::string str = "my#string";
std::for_each(str.begin(), str.end(), [] (char &ch) { if (ch == '#') ch = '\\'; }  );
// str now contains my\string

The for_each function code calls the lambda expression (indicated in yellow) for every character, and the lambda expression replaces the '#' with a '\'

Nenhum comentário:

Postar um comentário