Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

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.

import "strings"
x2 := strings.Replace(x, y, z, -1)

-1 means "no limit on the number of replacements".
This replaces non-overlapping instances of y.
import "strings"
x2 := strings.ReplaceAll(x, y, z)

This replaces non-overlapping instances of y.
#include <string>
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;
}

constexpr version which doesn't depend on regex

New implementation...