標準文字列内のテキストの検索と置換
さまざまなプログラミング シナリオでは、特定の文字または部分文字列を置換して文字列を操作することが不可欠になります。 C の標準文字列の場合、検索と置換操作を実行する効果的な方法があります。
std::replace 関数の使用
std::replace 関数は、文字列内の部分文字列を置き換える簡単な方法を提供します。 std::replace の構文は次のとおりです。
std::string& replace(std::size_t pos, std::size_t n, const std::string& str);
ここで、pos は開始位置を表し、n は置換する文字数を示し、str は置換文字列です。
例:
次の文字列について考えます:
std::string s("One hello, two hellos.");
「hello」のすべてのインスタンスを「world」に置き換えるには、次のコードを使用できます。
s.replace(s.find("hello"), s.find("hello") + 5, "world"); // Find the position of "hello", replace 5 characters (length of "hello") with "world"
boost::replace_all の使用
Boost ライブラリは、boost::replace_all 関数を使用して検索と置換操作を実行するためのより便利なオプションを提供します。文字列、検索する文字列、および置換する文字列を必要とします。
例:
すべての "foo" を "bar" に置換するには次の文字列:
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all を使用すると、次のように実行できます:
#include <boost/algorithm/string.hpp> // Include the Boost library ... boost::replace_all(target, "foo", "bar");
以上がC で文字列内のテキストを効率的に置換するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。