Logo

Programming-Idioms

History of Idiom 63 > diff from v59 to v60

Edit summary for version 60 by programming-idioms.org:
[C++] Sample values are a good fit for the demo

Version 59

2024-04-29, 23:49:38

Version 60

2024-05-12, 12:00:10

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Idiom #63 Replace fragment of a string

Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.

Variables
x2,x,y,z
Variables
x2,x,y,z
Extra Keywords
substring substitute
Extra Keywords
substring substitute
Imports
#include <string>
Imports
#include <string>
Code
constexpr std::string ReplaceAllCopy(const std::string& x, const std::string& y, const std::string& z) {
	auto x2 = x;
	size_t i = 0;

	while (true) {
		i = x2.find(y, i);
		if (i == std::string::npos) break;
		x2.replace(i, y.length(), z);
	}
	return x2;
}

static_assert(ReplaceAllCopy("AbAbAb", "b", "dd") == "AddAddAdd");
static_assert(ReplaceAllCopy("AbcAbc", "bc", "d") == "AdAd");
Code
constexpr std::string ReplaceAllCopy(const std::string& x, const std::string& y, const std::string& z) {
	auto x2 = x;
	size_t i = 0;

	while (true) {
		i = x2.find(y, i);
		if (i == std::string::npos) break;
		x2.replace(i, y.length(), z);
	}
	return x2;
}
Comments bubble
constexpr version which doesn't depend on regex
Comments bubble
constexpr version which doesn't depend on regex
Doc URL
https://en.cppreference.com/w/cpp/string/basic_string/replace
Doc URL
https://en.cppreference.com/w/cpp/string/basic_string/replace