ページ 11

std::string replace を用いた文字の置換

Posted: 2012年12月12日(水) 13:30
by chibago
お世話になっております。chibagoです。

以下の様なプログラムで文字の置換を行っております。

コード:

///header///
  static std::string replace_string(const std::string base,
                                    const std::string from,
                                    const std::string to);

///cpp////
  std::string StringUtil::replace_string(const std::string base,
                                            const std::string from,
					    const std::string to){
    std::string result = base;
    std::string::size_type pos = 0;
    while(pos = result.find(from, pos), pos != std::string::npos){
      result.replace(pos, from.length(), to);
      result += to.length();
     }
    return result;
  }

置換した文字を標準出力で確認すると問題なく動作しているのが
確認出来るのですが、テストケースで確認すると落ちてしまいます。

コード:

  std::string base = "Hello (XXX)!";
  std::string from = "(XXX)"; 
  std::string to = "World";
  std::string result = StringUtil::replace_string(base, from, to);
  std::string reference = "Hello World!";
  BOOST_CHECK_EQUAL(result, reference);
  std::cout<<result<<std::endl;
  std::cout<<reference<<std::endl;
  std::cout<<result.size()<<std::endl;
  std::cout<<reference.size()<<std::endl;

テスト自体は失敗に終わりますので、
照合した後に原因究明のため標準出力で情報を確認しております。
Hello World!
Hello World!
13
12
とくに、文章の後に余計なスペースが入っているわけでもないのですが、
置換した文のほうは、文字数が多くなっております。

何が原因なのでしょうか。
ご指導いただければ幸いです。

Re: std::string replace を用いた文字の置換

Posted: 2012年12月12日(水) 13:42
by h2so5
14行目は

コード:

pos += to.length();
の間違いではないでしょうか?

Re: std::string replace を用いた文字の置換

Posted: 2012年12月12日(水) 13:49
by chibago
h2so5様、
大変ありがとうございます。
ご指摘の通りでした。

自分では正しくコーディングしたつもりで、数時間悩んでいたのですが、
ただの凡ミスでした。

お恥ずかしいところをお見せして大変申し訳ございません。

今後ともよろしくお願いします。