2009-09-21 31 views
11

私は最後の1時間半を使って、C++のstringオブジェクトで単純な検索と置換を実行する方法を見つけようとしました。C++の文字列置換

私は3つの文字列オブジェクトを持っています。

string original, search_val, replace_val; 

私はsearch_valためoriginalに検索コマンドを実行し、replace_valですべての出現を置き換えたいです。

NB:純粋なC++のみの回答です。環境はMac OSX LeopardのXCodeです。

答えて

33

ループは、findと協力し、ここでは比較のために

void searchAndReplace(std::string& value, std::string const& search,std::string const& replace) 
{ 
    std::string::size_type next; 

    for(next = value.find(search);  // Try and find the first match 
     next != std::string::npos;  // next is npos if nothing was found 
     next = value.find(search,next) // search for the next match starting after 
              // the last match that was found. 
     ) 
    { 
     // Inside the loop. So we found a match. 
     value.replace(next,search.length(),replace); // Do the replacement. 
     next += replace.length();      // Move to just after the replace 
                 // This is the point were we start 
                 // the next search from. 
    } 
} 
+0

あなたのコードの仕組みを教えてください。 ありがとうございました:) –

+0

コメントが追加されました。 –

+0

これはちょっとしたものですが、関数名には非常にエレガントで整形式のコードでは少しずれて見えるタイプミス(Repalce)があります。 –

4
size_t start = 0; 
while(1) { 
    size_t where = original.find(search_val, start); 
    if(where==npos) { 
    break; 
    } 
    original.replace(where, search_val.size(), replace_val); 
    start = where + replace_val.size(); 
} 
+0

回答ありがとうございました –

1

を交換する必要があり、純粋なC関数です: http://www.pixelbeat.org/libs/string_replace.c

+1

「文字列補間」とはどういう意味ですか?私はあなたが提供したリンクのヘッダにそれを見つけました。あなたが見上げる –

+0

場合は、説明を取得する必要があり、「補間」。例えばシェル変数補間は、$ nameを "value"に置き換える処理です。 – pixelbeat

1

もう少しエレガント:

void searchAndReplace(std::string& value, std::string const& search,std::string const& replace) { 
    for(std::string::size_type idx = value.find(search);match 
     idx != std::string::npos;   
     next = value.find(search, idx + replace.size()) 
    ) 
     value.replace(next, search.size(), replace); 
} 
0

シンプル...

ただし、1文字のみの交換に限ります!

#include <algorithm> 
string foo = "abc.e"; 
std::replace(foo.begin(), foo.end(),'.','d'); 

result --> foo = "abcde"; 
1
#include <boost/algorithm/string.hpp> 

string newstring = boost::replace_all_copy(original, search_val, replace_val); 

か、あなたはその場で交換

boost::replace_all(original, search_val, replace_val); 
0

をしたい場合、これはより速く実行する可能性がありますし、望んでいた場合は、元のを保持します。

static std::string strreplace(const std::string &original, const std::string &pattern, const std::string &newtext) { 
std::stringstream ss;   
std::string::size_type last = 0; 
std::string::size_type it = original.find(pattern, last); 
while(it != original.npos) { 
    if(it-last > 0) { 
     ss << original.substr(last, it - last); 
     ss << newtext; 
    } 
    last = it + pattern.size();     
    it = original.find(pattern, last); 
} 
return ss.str(); 

}

0

これはおそらく、文字列のあなたの最も集中バージョンで置き換える:Aは、例でコードをテストした

for (string::size_type index = 0 ; 
         (index = value.find(from, index)) != string::npos ; 
         index += to.size()) 
    value.replace(index, from.size(), to); 
0

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 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; 
} 

パフォーマンスが必要な場合は、ここで入力された文字列を変更し、最適化機能である:あなたがしたい場合

は、文字列は、これを使用返さ

テスト:

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