absl::StrReplaceAll

Overload of StrReplaceAll() to accept a container of key/value replacement pairs (typically either an associative map or a std::vector of std::pair elements). A vector of pairs is generally more efficient.

Synopsis

Declared in <absl/strings/str_replace.h>

template<typename StrToStrMapping>
std::string
StrReplaceAll(
    std::string_view s,
    StrToStrMapping const& replacements);

Description

Examples:

std::map<const absl::string_view, const absl::string_view> replacements; replacements["$who"] = "Bob";] replacements["$count"] = "5";] replacements["#Noun"]= "Apples"; std::string s = absl::StrReplaceAll( "\(who bought \)count #Noun. Thanks $who!", replacements); EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);

// A std::vector of std::pair elements can be more efficient. std::vector<std::pair<const absl::string_view, std::string>> replacements; replacements.push_back({"&", "&amp;"}); replacements.push_back({"<", "&lt;"}); replacements.push_back({">", "&gt;"}); std::string s = absl::StrReplaceAll("if (ptr < &foo)", replacements); EXPECT_EQ("if (ptr &lt; &amp;foo)", s);

Return Value

A new string with the replacements applied.

Parameters

NameDescription
sThe string to search for replacements.
replacementsThe container of key/value pairs of sequences to replace.