Logo

Programming-Idioms

  • Java
  • Ruby
  • Haskell
  • JS
  • Lua
  • Php

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.

$x2 = str_replace($y, $z, $x);
String x2 = x.replace(y, z);

For regex, use String.replaceAll instead.
x2 = x.gsub(y, z)
import Data.List
allchanged [] _ _ = []
allchanged input from to = if isPrefixOf from input
  then to ++ allchanged (drop (length from) input) from to
  else head input : allchanged (tail input) from to

x2 = allchanged x y z
var x2 = x.replace(new RegExp(y, 'g'), z);

This works well only if y doesn't contain special regexp characters.
const x2 = x.replaceAll(y, z);
x2 = x:gsub(y,z)
#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...