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

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
chibago

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

#1

投稿記事 by chibago » 13年前

お世話になっております。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
とくに、文章の後に余計なスペースが入っているわけでもないのですが、
置換した文のほうは、文字数が多くなっております。

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

アバター
h2so5
副管理人
記事: 2212
登録日時: 15年前
住所: 東京
連絡を取る:

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

#2

投稿記事 by h2so5 » 13年前

14行目は

コード:

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

chibago

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

#3

投稿記事 by chibago » 13年前

h2so5様、
大変ありがとうございます。
ご指摘の通りでした。

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

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

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

閉鎖

“C言語何でも質問掲示板” へ戻る