を使用しstd::string
て、必要なメモリの再割り当てを処理し、boost
アルゴリズムを使用してすべてを簡単にすることができます。
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
std::string input("This is a Text with % Charakter and another % Charakter");
boost::replace_all(input, "%", "%%");
std::cout << input << std::endl;
}
出力:
これは %% Charakter と別の %% Charakter を持つテキストです
を使用できない場合は、 と を使用してboost
独自のバージョンを作成できます。replace_all
std::string::find
std::string::replace
template <typename C>
void replace_all(std::basic_string<C>& in,
const C* old_cstring,
const C* new_cstring)
{
std::basic_string<C> old_string(old_cstring);
std::basic_string<C> new_string(new_cstring);
typename std::basic_string<C>::size_type pos = 0;
while((pos = in.find(old_string, pos)) != std::basic_string<C>::npos)
{
in.replace(pos, old_string.size(), new_string);
pos += new_string.size();
}
}