Logo

Programming-Idioms

  • Pascal
  • Lua
  • 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.ReplaceAll(x, y, z)

This replaces non-overlapping instances of y.
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.
uses SysUtils;
x2 := StringReplace(x, y, z, [rfReplaceAll]);
x2 = x:gsub(y,z)
#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()

New implementation...