The standard C++ string class has 39 member functions, but never the one you need. A find-and-replace function one of those that is missing. Fortunately it can easily be implemented in terms of the find()
and replace()
methods:
#include <string> #include <iostream> #include <climits> std::string string_replace(const std::string& str, const std::string& match, const std::string& replacement, unsigned int max_replacements = UINT_MAX) { size_t pos = 0; std::string newstr = str; unsigned int replacements = 0; while ((pos = newstr.find(match, pos)) != std::string::npos && replacements < max_replacements) { newstr.replace(pos, match.length(), replacement); pos += replacement.length(); replacements++; } return newstr; }
The Boost library has replace_all()
, which does the replacement in-place, modifying the original string.
The pystring library has replace(), which not surprisingly works the same way as the Python string.replace()
method.
Related
- How to split a string in C++
- How to do string formatting in C++
- How to replace all occurrences of a character in a std::string
- How to do case-insensitive string comparison in C++
- How to concatenate a string and an int in C++
- How to convert a string to lower or upper case in C++
- How to trim a std::string in C++
- How to get a const char* or a char* from a std::string
- How to convert an int to a std::string in C++