103

の部分文字列のすべての出現箇所を別の文字列に置き換える方法はありstd::stringますか?

例えば:

void SomeFunction(std::string& str)
{
   str = str.replace("hello", "world"); //< I'm looking for something nice like this
}
4

10 に答える 10

163
#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");

これがreplace_allの公式ドキュメントです。

于 2010-11-27T03:03:16.660 に答える
80

独自の置換を実装してみませんか?

void myReplace(std::string& str,
               const std::string& oldStr,
               const std::string& newStr)
{
  std::string::size_type pos = 0u;
  while((pos = str.find(oldStr, pos)) != std::string::npos){
     str.replace(pos, oldStr.length(), newStr);
     pos += newStr.length();
  }
}
于 2009-09-29T19:21:01.613 に答える
41

C++11 では、次の呼び出しを使用してワンライナーでこれを行うことができますregex_replace

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

出力:

Removeallspaces
于 2016-06-21T17:52:37.363 に答える
19

変更された文字列を返さないのはなぜですか?

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

パフォーマンスが必要な場合は、入力文字列を変更する最適化された関数を次に示します。文字列のコピーは作成されません。

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

テスト:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

出力:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
于 2013-02-04T00:32:45.457 に答える
6

私のテンプレート化されたインラインインプレース検索と置換:

template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
    int num=0;
    typename T::size_t fLen = find.size();
    typename T::size_t rLen = replace.size();
    for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
        num++;
        source.replace(pos, fLen, replace);
    }
    return num;
}

置換されたアイテムの数を返します(これを連続して実行する場合などに使用します)。それを使用するには:

std::string str = "one two three";
int n = findAndReplace(str, "one", "1");
于 2010-11-11T15:46:31.877 に答える
3

最も簡単な方法(あなたが書いたものに近いものを提供する)は、Boost.Regex、具体的にはregex_replaceを使用することです。

std :: stringにはfind()メソッドとreplace()メソッドが組み込まれていますが、インデックスと文字列の長さを処理する必要があるため、操作が面倒です。

于 2009-09-29T19:18:50.307 に答える
3

これでうまくいくと思います。パラメータとしてconstchar*を取ります。

//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
   //ASSERT(find != NULL);
   //ASSERT(replace != NULL);
   size_t findLen = strlen(find);
   size_t replaceLen = strlen(replace);
   size_t pos = 0;

   //search for the next occurrence of find within source
   while ((pos = source.find(find, pos)) != std::string::npos)
   {
      //replace the found string with the replacement
      source.replace( pos, findLen, replace );

      //the next line keeps you from searching your replace string, 
      //so your could replace "hello" with "hello world" 
      //and not have it blow chunks.
      pos += replaceLen; 
   }
}
于 2009-09-29T19:26:00.513 に答える