如何使用 C++ std::ranges 替换字符串中的子字符串?

Fli*_*lip 2 c++ string replace c++20 std-ranges

我知道如何使用 std::replace 替换向量中的字符,如下所示:ranges::replace

我会撒谎对字符串中的子字符串做类似的事情。例如:

std::string str{"The quick brown fox jumped over the lazy dog.";
std::ranges::replace(str, "the", "a");
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

错误:与调用 '(const std::ranges::__replace_fn) (std::string&, const char [4], const char [2])' 不匹配

或者如果我使用字符串

错误:与调用 '(const std::ranges::__replace_fn) (std::string&, std::string&, std::string&)' 不匹配

它适用于字符,但不适用于子字符串。

有任何想法吗?

我已成功使用循环 andstring.findstring.replace,但想使用范围。

joe*_*ech 8

std::ranges::replace替换范围中的元素,您想要将一个子范围替换为另一个子范围。据我所知,目前标准库中还没有它的算法。

使用std::regex

我只想使用std::regex

std::string str{"The quick brown fox jumped over the lazy dog."};
std::cout << std::regex_replace(str,std::regex("the"), "a") << std::endl;
Run Code Online (Sandbox Code Playgroud)
The quick brown fox jumped over a lazy dog.
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/q4c6dzzPP

使用std::ranges

如果您确实使用std::ranges,您可以按照给定模式分割范围,在分割处插入替换,然后加入范围。

std::ranges在 C++23 中使用:

C++23 方便地提供了一个函数std::views::join_with (截至撰写本文时尚未广泛采用)

The quick brown fox jumped over a lazy dog.
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/nd8zardE5

std::ranges在 C++20 中使用:

你也可以让它在 C++20 中工作,你只需要多做一些工作:

auto replace_view(std::string_view str, std::string_view pattern, std::string_view replacement)
{
    return str | std::views::split(pattern) | std::views::join_with(replacement);
}
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/j1WMWdW1h