0

char 配列のパーセント記号を 2 つの記号に置き換えてみたいと思い%%ます。%符号が問題になるので、出力char配列として書くと。したがって、パーセンテージ記号は、文字列を使用せずに 2 つの記号に置き換える必要があり%%ます。

// This array causes dump because of '%'
char input[] = "This is a Text with % Charakter";
//Therefore Percent Sign(%) must be replaced with two %%. 
4

1 に答える 1

6

を使用し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_allstd::string::findstd::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();
  }
}
于 2013-08-28T10:00:00.133 に答える