Logo

Programming-Idioms

  • Pascal
  • C++
  • Elixir
  • JS

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 = String.replace(x, y, z)
uses SysUtils;
x2 := StringReplace(x, y, z, [rfReplaceAll]);
#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
#include <string>
#include <iterator>
#include <regex>
#include <iostream>
std::stringstream s;
std::regex_replace(std::ostreambuf_iterator<char>(s), x.begin(), x.end(), y, z);
auto x2 = s.str()
const x2 = x.replaceAll(y, z);
var x2 = x.replace(new RegExp(y, 'g'), z);

This works well only if y doesn't contain special regexp characters.
using System;
string x2 = x.Replace(y, z, StringComparison.Ordinal);

It is best practice to explicitly specify the string comparison method when working with strings in .NET.

New implementation...