Taskintro
Replace a substring
Also called replace text, replaceAll, string replace, substitute a substring, find and replace, str.replace.
Replace each match, or only the first match, of a substring in a string with other text, and know which replace functions take a pattern and which characters of the new text have a special meaning.
- Evidence
- Code in 10 languages
Task
Replace a substring in a string with other text. The function replace(s, old, new) returns s with each match of old replaced by new, and replace_first(s, old, new) replaces only the first match. For example, replace("a-b-c", "-", "+") is "a+b+c", and replace_first("a-b-c", "-", "+") is "a+b-c".
The search is literal and case-sensitive, and it goes from left to right. After a match, the search goes on after the end of the match, so the matches do not overlap, and the new text is not searched again. old is not empty, because the languages do not agree on what a replace of the empty string does. The characters of new have no special meaning, so $, & and \ stay as they are.
Solutions
| Language | All matches | First match | Literal? |
|---|---|---|---|
| Python | s.replace(old, new) |
s.replace(old, new, 1) |
yes |
| JavaScript, TypeScript | s.replaceAll(old, () => nw) |
s.replace(old, () => nw) |
the pattern yes, the new text no |
| Java | s.replace(old, nw) |
indexOf and substring |
replace yes, replaceAll and replaceFirst no |
| C# | s.Replace(old, nw, StringComparison.Ordinal) |
IndexOf and string.Concat |
yes |
| Go | strings.ReplaceAll(s, old, nw) |
strings.Replace(s, old, nw, 1) |
yes |
| Rust | s.replace(old, new) |
s.replacen(old, new, 1) |
yes |
| C | a loop with strstr and memcpy |
the same loop, once | yes |
| C++ | a loop with find and += |
the same loop, once | yes |
| Bash | ${s//"$old"/$new} |
${s/"$old"/$new} |
only with quotes |
- Python.
str.replacereturns "a copy of the string with all occurrences of substring old replaced by new"1. "If count is given, only the first count occurrences are replaced"1, soreplace_firstpasses 1. - JavaScript and TypeScript.
replacewith a string pattern changes one match: "If pattern is a string, only the first occurrence will be replaced"2.replaceAllchanges each match. In a replacement string,$&"Inserts the matched substring"2, so the code passes a function that returnsnw. "The function's result (return value) will be used as the replacement string"2, and the result has no special patterns. - Java.
replace(CharSequence, CharSequence)"Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence"3. Java has no literalreplaceFirst, so the code finds the first match withindexOfand joins the two parts andnw. - C#.
Replace"Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string"4. The code passesStringComparison.Ordinal, so the search compares code units. For the first match, the code finds the index withIndexOfand joins the parts withstring.Concat. - Go. "Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new"5.
ReplaceAllisReplacewith no limit. - Rust.
replace"Replaces all matches of a pattern with another string"6, andreplacen"Replaces first N matches of a pattern with another string"6. Both return a newString. - C. C has no replace function. The code makes two passes with
strstr. The first pass counts the matches, and the second pass copies the text between the matches and the new text into one allocation of the right size. The caller frees the result. - C++.
std::string::replacereplaces a range of positions, not a match, so the code uses a loop. It appends the text before each match andnew_to the result, and it searches again after the end of the match. - Bash. In
${parameter//pattern/string}, "The longest match of pattern in the expanded value is replaced with string"7.patternis a glob, and "The special pattern characters must be quoted if they are to be matched literally"7, so the function quotesold. With the optionpatsub_replacementof Bash 5.2, "any unquoted instances of ‘&’ in string are replaced with the matching portion of pattern"7. The function turns the option off in a subshell and gives the new text in a variable.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of replace_first are in cases/first.jsonl.
noneandfirst-none: no match gives the string with no change.empty-s: the empty string has no match of a non-emptyold.delete: an emptynewdeletes each match.new-contains-old:aXawithXreplaced byXXXisaXXXa. The search does not look at the new text again, so the replace ends.overlapandoverlap-odd:aaaawithaareplaced bybisbb, andaaagivesba. The matches do not overlap, and the search starts at the left.case-sensitive:hellodoes not matchHello.non-asciiandastral: the search compares whole code points, so a replace oféor of an emoji changes all of its bytes or code units.combiningandprecomposed: incafe\u0301, theeis a separate code point, so a replace ofewithEgivesEwith the accent on it. The precomposed\u00e9has noein it, so the same replace changes nothing.dot,dollar,ampersandandbackslash: these characters have a special meaning in a regex or in a replacement string, so a solution that takes a pattern fails these cases.
Pitfalls
- Python strings are immutable. "Strings are immutable sequences of Unicode code points"1, so
replacereturns a new string and does not changes. A call that does not use the result does nothing. The matches do not overlap, so'aaaa'.replace('aa', 'a')givesaa, nota:
s = "a-b-c"
s.replace("-", "+")
print(s)
s = s.replace("-", "+", 1)
print(s)
print("aaaa".replace("aa", "a"))
a-b-c
a+b-c
aa
- JavaScript replace with a string changes only the first match. Use
replaceAll.$&in the new text inserts the match, so pass a function if the new text comes from a user. "If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown"8:
const s = "a-b-c";
console.log(s.replace("-", "+"), s.replaceAll("-", "+"));
console.log("price".replace("price", "$&!"), "price".replace("price", () => "$&!"));
try {
s.replaceAll(/-/, "+");
} catch (e) {
console.log(e.name);
}
a+b-c a+b+c
price! $&!
TypeError
- Java replaceAll takes a regex. The regex
.matches any character, so areplaceAllof.with-replaces all of the string. "Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string"3. A$5with no group 5 throws an exception. Usereplacefor literal text:
public class Main {
public static void main(String[] args) {
String s = "a.b.c";
System.out.println(s.replace(".", "-") + " " + s.replaceAll(".", "-"));
System.out.println(s.replaceAll("\\.", "-"));
try {
"cost".replaceAll("cost", "$5");
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
a-b-c -----
a-b-c
IndexOutOfBoundsException
- C# Replace throws for an empty old value. It throws
ArgumentExceptionwhen "oldValue is the empty string"4. "If newValue is null, all occurrences of oldValue are removed"4.Replace(char, char)changes single characters:
string s = "a-b-c";
Console.WriteLine(s.Replace("-", null));
Console.WriteLine(s.Replace('-', '+'));
try
{
s.Replace("", "+");
}
catch (ArgumentException e)
{
Console.WriteLine(e.GetType().Name);
}
abc
a+b+c
ArgumentException
- Go and Rust insert the new text at each position for an empty old. In Go, an empty old "matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string"5. In
strings.Replace, "If n < 0, there is no limit on the number of replacements"5:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("a-b-c", "-", "+", 1), strings.Replace("a-b-c", "-", "+", -1))
fmt.Println(strings.ReplaceAll("abc", "", "-"))
fmt.Println(strings.ReplaceAll("naïve", "", "-"))
}
a+b-c a+b+c
-a-b-c-
-n-a-ï-v-e-
- Rust replace takes any pattern. The old text can be a
&str, acharor a closure, so one call can replace each digit.replace"creates a new String"6, and the original&strdoes not change:
fn main() {
let s = "a-b-c";
let t = s.replace('-', "+");
println!("{s} {t}");
println!("{}", s.replacen('-', "+", 1));
println!("{}", "abc".replace("", "-"));
println!("{}", "a1b22c".replace(|c: char| c.is_ascii_digit(), "#"));
}
a-b-c a+b+c
a+b-c
-a-b-c-
a#b##c
- C can replace in place only when the length does not change. A loop with
strchr, which "Finds the first occurrence of ch"9, can change each-to+in achararray. A longer or shorter new text needs a new buffer, as in the solution:
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "a-b-c";
for (char *p = strchr(s, '-'); p != NULL; p = strchr(p + 1, '-')) {
*p = '+';
}
printf("%s\n", s);
}
a+b+c
- C++ std::string::replace takes positions, not text. It "Replaces the characters in the range"10 that a position and a count give. To replace single characters, use
std::ranges::replace, which replaces "all elements that are equal to old_value"11:
#include <algorithm>
#include <print>
#include <string>
int main() {
std::string s = "Hello, world";
s.replace(7, 5, "there");
std::println("{}", s);
std::string t = "a-b-c";
std::ranges::replace(t, '-', '+');
std::println("{}", t);
}
Hello, there
a+b+c
- Bash reads the old text as a glob. In
${s//*/-}, the*matches all of the string, so the result is one-. A*in quotes, or a variable in quotes, matches only the character*:
s='a*b*c'
echo "${s//*/-}"
echo "${s//"*"/-}"
p='*'
echo "${s//$p/-}" "${s//"$p"/-}"
-
a-b-c
- a-b-c
Related tasks
- Search for a substring: find the index of a match without a change.
- Split a string: cut a string at each match of a separator.
- Remove characters from a string: delete characters, which is a replace with the empty string.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-a-substring/.
def replace(s: str, old: str, new: str) -> str:
"""Return s with each match of old replaced by new."""
return s.replace(old, new)
def replace_first(s: str, old: str, new: str) -> str:
"""Return s with the first match of old replaced by new."""
# The third argument is the largest number of matches to replace.
return s.replace(old, new, 1)
test_replace.py 46 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-a-substring/.
import pytest
from replace import replace, replace_first
# U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
ALL = {
"all": ("a-b-c", "-", "+", "a+b+c"),
"word": ("Hello, world", "world", "there", "Hello, there"),
"none": ("abc", "x", "y", "abc"),
"empty-s": ("", "a", "b", ""),
"delete": ("a-b-c", "-", "", "abc"),
"new-contains-old": ("aXa", "X", "XXX", "aXXXa"),
"overlap": ("aaaa", "aa", "b", "bb"),
"overlap-odd": ("aaa", "aa", "b", "ba"),
"case-sensitive": ("Hello hello", "hello", "bye", "Hello bye"),
"non-ascii": ("naïve caf\u00e9", "\u00e9", "e", "naïve cafe"),
"astral": ("a\U0001f642b\U0001f642", "\U0001f642", "!", "a!b!"),
"combining": ("cafe\u0301", "e", "E", "cafE\u0301"),
"precomposed": ("caf\u00e9", "e", "E", "caf\u00e9"),
"dot": ("a.b.c", ".", "-", "a-b-c"),
"dollar": ("price", "price", "$&!", "$&!"),
"ampersand": ("a-b", "-", "&", "a&b"),
"backslash": ("a/b", "/", "\\", "a\\b"),
}
FIRST = {
"first-only": ("a-b-c", "-", "+", "a+b-c"),
"first-none": ("abc", "x", "y", "abc"),
"first-overlap": ("aaa", "aa", "b", "ba"),
"first-astral": ("\U0001f642\U0001f642", "\U0001f642", "x", "x\U0001f642"),
"first-dollar": ("a.b", ".", "$&", "a$&b"),
}
@pytest.mark.parametrize("name", ALL)
def test_replace(name):
s, old, new, want = ALL[name]
assert replace(s, old, new) == want
@pytest.mark.parametrize("name", FIRST)
def test_replace_first(name):
s, old, new, want = FIRST[name]
assert replace_first(s, old, new) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#include "replace.hpp"
namespace {
// replace_n replaces at most limit matches. It appends the text between the
// matches and the new text to the result, and it searches again after the end
// of each match.
std::string replace_n(std::string_view s, std::string_view old, std::string_view new_, std::size_t limit) {
std::string out;
std::size_t from = 0;
for (std::size_t n = 0; n < limit; n++) {
std::size_t i = s.find(old, from);
if (i == std::string_view::npos) {
break;
}
out += s.substr(from, i - from);
out += new_;
from = i + old.size();
}
out += s.substr(from);
return out;
}
} // namespace
std::string replace(std::string_view s, std::string_view old, std::string_view new_) {
return replace_n(s, old, new_, std::string_view::npos);
}
std::string replace_first(std::string_view s, std::string_view old, std::string_view new_) {
return replace_n(s, old, new_, 1);
}
replace.hpp 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#ifndef REPLACE_HPP
#define REPLACE_HPP
#include <string>
#include <string_view>
// replace returns s with each match of old replaced by new_. old must not be
// empty.
std::string replace(std::string_view s, std::string_view old, std::string_view new_);
// replace_first is like replace, but it replaces only the first match.
std::string replace_first(std::string_view s, std::string_view old, std::string_view new_);
#endif
test_replace.cpp 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#include "replace.hpp"
#include <iostream>
#include <string>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, const std::string &got, std::string_view want) {
if (got != want) {
std::cerr << "case " << name << ": got [" << got << "], want [" << want << "]\n";
failures++;
}
}
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
int main() {
check("all", replace("a-b-c", "-", "+"), "a+b+c");
check("word", replace("Hello, world", "world", "there"), "Hello, there");
check("none", replace("abc", "x", "y"), "abc");
check("empty-s", replace("", "a", "b"), "");
check("delete", replace("a-b-c", "-", ""), "abc");
check("new-contains-old", replace("aXa", "X", "XXX"), "aXXXa");
check("overlap", replace("aaaa", "aa", "b"), "bb");
check("overlap-odd", replace("aaa", "aa", "b"), "ba");
check("case-sensitive", replace("Hello hello", "hello", "bye"), "Hello bye");
check("non-ascii", replace("naïve caf\xc3\xa9", "\xc3\xa9", "e"), "naïve cafe");
check("astral", replace("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82", "!"), "a!b!");
check("combining", replace("cafe\xcc\x81", "e", "E"), "cafE\xcc\x81");
check("precomposed", replace("caf\xc3\xa9", "e", "E"), "caf\xc3\xa9");
check("dot", replace("a.b.c", ".", "-"), "a-b-c");
check("dollar", replace("price", "price", "$&!"), "$&!");
check("ampersand", replace("a-b", "-", "&"), "a&b");
check("backslash", replace("a/b", "/", "\\"), "a\\b");
check("first-only", replace_first("a-b-c", "-", "+"), "a+b-c");
check("first-none", replace_first("abc", "x", "y"), "abc");
check("first-overlap", replace_first("aaa", "aa", "b"), "ba");
check("first-astral", replace_first("\xf0\x9f\x99\x82\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82", "x"), "x\xf0\x9f\x99\x82");
check("first-dollar", replace_first("a.b", ".", "$&"), "a$&b");
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
/** Replaces a substring in a string. The search is literal. */
public final class Replace {
private Replace() {}
/** Returns s with each match of old replaced by nw. */
public static String replace(String s, String old, String nw) {
// replace takes literal text. replaceAll and replaceFirst take a regex.
return s.replace(old, nw);
}
/** Returns s with the first match of old replaced by nw. */
public static String replaceFirst(String s, String old, String nw) {
int i = s.indexOf(old);
if (i < 0) {
return s;
}
return s.substring(0, i) + nw + s.substring(i + old.length());
}
}
ReplaceTest.java 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ReplaceTest {
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
static Stream<Arguments> all() {
return Stream.of(
Arguments.of("all", "a-b-c", "-", "+", "a+b+c"),
Arguments.of("word", "Hello, world", "world", "there", "Hello, there"),
Arguments.of("none", "abc", "x", "y", "abc"),
Arguments.of("empty-s", "", "a", "b", ""),
Arguments.of("delete", "a-b-c", "-", "", "abc"),
Arguments.of("new-contains-old", "aXa", "X", "XXX", "aXXXa"),
Arguments.of("overlap", "aaaa", "aa", "b", "bb"),
Arguments.of("overlap-odd", "aaa", "aa", "b", "ba"),
Arguments.of("case-sensitive", "Hello hello", "hello", "bye", "Hello bye"),
Arguments.of("non-ascii", "naïve caf\u00e9", "\u00e9", "e", "naïve cafe"),
Arguments.of("astral", "a\ud83d\ude42b\ud83d\ude42", "\ud83d\ude42", "!", "a!b!"),
Arguments.of("combining", "cafe\u0301", "e", "E", "cafE\u0301"),
Arguments.of("precomposed", "caf\u00e9", "e", "E", "caf\u00e9"),
Arguments.of("dot", "a.b.c", ".", "-", "a-b-c"),
Arguments.of("dollar", "price", "price", "$&!", "$&!"),
Arguments.of("ampersand", "a-b", "-", "&", "a&b"),
Arguments.of("backslash", "a/b", "/", "\\", "a\\b"));
}
static Stream<Arguments> first() {
return Stream.of(
Arguments.of("first-only", "a-b-c", "-", "+", "a+b-c"),
Arguments.of("first-none", "abc", "x", "y", "abc"),
Arguments.of("first-overlap", "aaa", "aa", "b", "ba"),
Arguments.of("first-astral", "\ud83d\ude42\ud83d\ude42", "\ud83d\ude42", "x", "x\ud83d\ude42"),
Arguments.of("first-dollar", "a.b", ".", "$&", "a$&b"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("all")
void replace(String name, String s, String old, String nw, String want) {
assertEquals(want, Replace.replace(s, old, nw));
}
@ParameterizedTest(name = "{0}")
@MethodSource("first")
void replaceFirst(String name, String s, String old, String nw, String want) {
assertEquals(want, Replace.replaceFirst(s, old, nw));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#include "replace.h"
#include <stdlib.h>
#include <string.h>
// replace_n replaces at most limit matches. The first pass counts the
// matches, so the second pass can write into one allocation of the right size.
static char *replace_n(const char *s, const char *old, const char *new_, size_t limit) {
size_t old_len = strlen(old);
size_t new_len = strlen(new_);
size_t count = 0;
for (const char *p = strstr(s, old); p != NULL && count < limit; p = strstr(p + old_len, old)) {
count++;
}
size_t len = strlen(s) - count * old_len + count * new_len;
char *out = malloc(len + 1);
if (out == NULL) {
return NULL;
}
char *w = out;
const char *p = s;
for (size_t i = 0; i < count; i++) {
const char *m = strstr(p, old);
memcpy(w, p, (size_t)(m - p));
w += m - p;
memcpy(w, new_, new_len);
w += new_len;
p = m + old_len;
}
strcpy(w, p);
return out;
}
char *replace(const char *s, const char *old, const char *new_) {
return replace_n(s, old, new_, (size_t)-1);
}
char *replace_first(const char *s, const char *old, const char *new_) {
return replace_n(s, old, new_, 1);
}
replace.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#ifndef REPLACE_H
#define REPLACE_H
#include <stddef.h>
// replace returns s with each match of old replaced by new, in a new string
// that the caller frees. old must not be empty. It returns NULL if the
// allocation fails.
char *replace(const char *s, const char *old, const char *new_);
// replace_first is like replace, but it replaces only the first match.
char *replace_first(const char *s, const char *old, const char *new_);
#endif
test_replace.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
#include "replace.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, char *got, const char *want) {
if (got == NULL || strcmp(got, want) != 0) {
fprintf(stderr, "case %s: got [%s], want [%s]\n", name, got ? got : "NULL", want);
failures++;
}
free(got);
}
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
int main(void) {
check("all", replace("a-b-c", "-", "+"), "a+b+c");
check("word", replace("Hello, world", "world", "there"), "Hello, there");
check("none", replace("abc", "x", "y"), "abc");
check("empty-s", replace("", "a", "b"), "");
check("delete", replace("a-b-c", "-", ""), "abc");
check("new-contains-old", replace("aXa", "X", "XXX"), "aXXXa");
check("overlap", replace("aaaa", "aa", "b"), "bb");
check("overlap-odd", replace("aaa", "aa", "b"), "ba");
check("case-sensitive", replace("Hello hello", "hello", "bye"), "Hello bye");
check("non-ascii", replace("naïve caf\xc3\xa9", "\xc3\xa9", "e"), "naïve cafe");
check("astral", replace("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82", "!"), "a!b!");
check("combining", replace("cafe\xcc\x81", "e", "E"), "cafE\xcc\x81");
check("precomposed", replace("caf\xc3\xa9", "e", "E"), "caf\xc3\xa9");
check("dot", replace("a.b.c", ".", "-"), "a-b-c");
check("dollar", replace("price", "price", "$&!"), "$&!");
check("ampersand", replace("a-b", "-", "&"), "a&b");
check("backslash", replace("a/b", "/", "\\"), "a\\b");
check("first-only", replace_first("a-b-c", "-", "+"), "a+b-c");
check("first-none", replace_first("abc", "x", "y"), "abc");
check("first-overlap", replace_first("aaa", "aa", "b"), "ba");
check("first-astral", replace_first("\xf0\x9f\x99\x82\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82", "x"), "x\xf0\x9f\x99\x82");
check("first-dollar", replace_first("a.b", ".", "$&"), "a$&b");
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
using System;
/// <summary>Replaces a substring in a string. The search is ordinal.</summary>
public static class Replace
{
/// <summary>Returns s with each match of old replaced by nw.</summary>
public static string All(string s, string old, string nw)
{
return s.Replace(old, nw, StringComparison.Ordinal);
}
/// <summary>Returns s with the first match of old replaced by nw.</summary>
public static string First(string s, string old, string nw)
{
int i = s.IndexOf(old, StringComparison.Ordinal);
if (i < 0)
{
return s;
}
return string.Concat(s.AsSpan(0, i), nw, s.AsSpan(i + old.Length));
}
}
ReplaceTests.cs 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
using Xunit;
public sealed class ReplaceTests
{
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
public static TheoryData<string, string, string, string, string> All => new()
{
{ "all", "a-b-c", "-", "+", "a+b+c" },
{ "word", "Hello, world", "world", "there", "Hello, there" },
{ "none", "abc", "x", "y", "abc" },
{ "empty-s", "", "a", "b", "" },
{ "delete", "a-b-c", "-", "", "abc" },
{ "new-contains-old", "aXa", "X", "XXX", "aXXXa" },
{ "overlap", "aaaa", "aa", "b", "bb" },
{ "overlap-odd", "aaa", "aa", "b", "ba" },
{ "case-sensitive", "Hello hello", "hello", "bye", "Hello bye" },
{ "non-ascii", "naïve caf\u00e9", "\u00e9", "e", "naïve cafe" },
{ "astral", "a\U0001f642b\U0001f642", "\U0001f642", "!", "a!b!" },
{ "combining", "cafe\u0301", "e", "E", "cafE\u0301" },
{ "precomposed", "caf\u00e9", "e", "E", "caf\u00e9" },
{ "dot", "a.b.c", ".", "-", "a-b-c" },
{ "dollar", "price", "price", "$&!", "$&!" },
{ "ampersand", "a-b", "-", "&", "a&b" },
{ "backslash", "a/b", "/", "\\", "a\\b" },
};
public static TheoryData<string, string, string, string, string> First => new()
{
{ "first-only", "a-b-c", "-", "+", "a+b-c" },
{ "first-none", "abc", "x", "y", "abc" },
{ "first-overlap", "aaa", "aa", "b", "ba" },
{ "first-astral", "\U0001f642\U0001f642", "\U0001f642", "x", "x\U0001f642" },
{ "first-dollar", "a.b", ".", "$&", "a$&b" },
};
[Theory]
[MemberData(nameof(All))]
public void All_(string name, string s, string old, string nw, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Replace.All(s, old, nw));
}
[Theory]
[MemberData(nameof(First))]
public void First_(string name, string s, string old, string nw, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Replace.First(s, old, nw));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
// The replacement is a function, so the patterns such as $& in nw have no
// special meaning.
/** Returns s with each match of old replaced by nw. */
export function replace(s, old, nw) {
return s.replaceAll(old, () => nw);
}
/** Returns s with the first match of old replaced by nw. */
export function replaceFirst(s, old, nw) {
// With a string pattern, replace changes only the first match.
return s.replace(old, () => nw);
}
replace.test.js 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { replace, replaceFirst } from "./replace.js";
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const all = [
["all", "a-b-c", "-", "+", "a+b+c"],
["word", "Hello, world", "world", "there", "Hello, there"],
["none", "abc", "x", "y", "abc"],
["empty-s", "", "a", "b", ""],
["delete", "a-b-c", "-", "", "abc"],
["new-contains-old", "aXa", "X", "XXX", "aXXXa"],
["overlap", "aaaa", "aa", "b", "bb"],
["overlap-odd", "aaa", "aa", "b", "ba"],
["case-sensitive", "Hello hello", "hello", "bye", "Hello bye"],
["non-ascii", "naïve caf\u00e9", "\u00e9", "e", "naïve cafe"],
["astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "!", "a!b!"],
["combining", "cafe\u0301", "e", "E", "cafE\u0301"],
["precomposed", "caf\u00e9", "e", "E", "caf\u00e9"],
["dot", "a.b.c", ".", "-", "a-b-c"],
["dollar", "price", "price", "$&!", "$&!"],
["ampersand", "a-b", "-", "&", "a&b"],
["backslash", "a/b", "/", "\\", "a\\b"],
];
const first = [
["first-only", "a-b-c", "-", "+", "a+b-c"],
["first-none", "abc", "x", "y", "abc"],
["first-overlap", "aaa", "aa", "b", "ba"],
["first-astral", "\u{1f642}\u{1f642}", "\u{1f642}", "x", "x\u{1f642}"],
["first-dollar", "a.b", ".", "$&", "a$&b"],
];
for (const [name, s, old, nw, want] of all) {
test(name, () => {
assert.equal(replace(s, old, nw), want);
});
}
for (const [name, s, old, nw, want] of first) {
test(name, () => {
assert.equal(replaceFirst(s, old, nw), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
// The replacement is a function, so the patterns such as $& in nw have no
// special meaning.
/** Returns s with each match of old replaced by nw. */
export function replace(s: string, old: string, nw: string): string {
return s.replaceAll(old, () => nw);
}
/** Returns s with the first match of old replaced by nw. */
export function replaceFirst(s: string, old: string, nw: string): string {
// With a string pattern, replace changes only the first match.
return s.replace(old, () => nw);
}
replace.test.ts 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { replace, replaceFirst } from "./replace.ts";
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
const all = [
["all", "a-b-c", "-", "+", "a+b+c"],
["word", "Hello, world", "world", "there", "Hello, there"],
["none", "abc", "x", "y", "abc"],
["empty-s", "", "a", "b", ""],
["delete", "a-b-c", "-", "", "abc"],
["new-contains-old", "aXa", "X", "XXX", "aXXXa"],
["overlap", "aaaa", "aa", "b", "bb"],
["overlap-odd", "aaa", "aa", "b", "ba"],
["case-sensitive", "Hello hello", "hello", "bye", "Hello bye"],
["non-ascii", "naïve caf\u00e9", "\u00e9", "e", "naïve cafe"],
["astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "!", "a!b!"],
["combining", "cafe\u0301", "e", "E", "cafE\u0301"],
["precomposed", "caf\u00e9", "e", "E", "caf\u00e9"],
["dot", "a.b.c", ".", "-", "a-b-c"],
["dollar", "price", "price", "$&!", "$&!"],
["ampersand", "a-b", "-", "&", "a&b"],
["backslash", "a/b", "/", "\\", "a\\b"],
];
const first = [
["first-only", "a-b-c", "-", "+", "a+b-c"],
["first-none", "abc", "x", "y", "abc"],
["first-overlap", "aaa", "aa", "b", "ba"],
["first-astral", "\u{1f642}\u{1f642}", "\u{1f642}", "x", "x\u{1f642}"],
["first-dollar", "a.b", ".", "$&", "a$&b"],
];
for (const [name, s, old, nw, want] of all) {
test(name, () => {
assert.equal(replace(s, old, nw), want);
});
}
for (const [name, s, old, nw, want] of first) {
test(name, () => {
assert.equal(replaceFirst(s, old, nw), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
// Package replace replaces a substring in a string.
package replace
import "strings"
// Replace returns s with each match of old replaced by nw.
func Replace(s, old, nw string) string {
return strings.ReplaceAll(s, old, nw)
}
// ReplaceFirst returns s with the first match of old replaced by nw.
func ReplaceFirst(s, old, nw string) string {
// The last argument is the largest number of matches to replace.
return strings.Replace(s, old, nw, 1)
}
replace_test.go 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
package replace
import "testing"
type replaceCase struct {
name, s, old, nw, want string
}
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
var all = []replaceCase{
{"all", "a-b-c", "-", "+", "a+b+c"},
{"word", "Hello, world", "world", "there", "Hello, there"},
{"none", "abc", "x", "y", "abc"},
{"empty-s", "", "a", "b", ""},
{"delete", "a-b-c", "-", "", "abc"},
{"new-contains-old", "aXa", "X", "XXX", "aXXXa"},
{"overlap", "aaaa", "aa", "b", "bb"},
{"overlap-odd", "aaa", "aa", "b", "ba"},
{"case-sensitive", "Hello hello", "hello", "bye", "Hello bye"},
{"non-ascii", "naïve caf\u00e9", "\u00e9", "e", "naïve cafe"},
{"astral", "a\U0001f642b\U0001f642", "\U0001f642", "!", "a!b!"},
{"combining", "cafe\u0301", "e", "E", "cafE\u0301"},
{"precomposed", "caf\u00e9", "e", "E", "caf\u00e9"},
{"dot", "a.b.c", ".", "-", "a-b-c"},
{"dollar", "price", "price", "$&!", "$&!"},
{"ampersand", "a-b", "-", "&", "a&b"},
{"backslash", "a/b", "/", "\\", "a\\b"},
}
var first = []replaceCase{
{"first-only", "a-b-c", "-", "+", "a+b-c"},
{"first-none", "abc", "x", "y", "abc"},
{"first-overlap", "aaa", "aa", "b", "ba"},
{"first-astral", "\U0001f642\U0001f642", "\U0001f642", "x", "x\U0001f642"},
{"first-dollar", "a.b", ".", "$&", "a$&b"},
}
func TestReplace(t *testing.T) {
for _, c := range all {
if got := Replace(c.s, c.old, c.nw); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestReplaceFirst(t *testing.T) {
for _, c := range first {
if got := ReplaceFirst(c.s, c.old, c.nw); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
/// Returns s with each match of old replaced by new.
pub fn replace(s: &str, old: &str, new: &str) -> String {
s.replace(old, new)
}
/// Returns s with the first match of old replaced by new.
pub fn replace_first(s: &str, old: &str, new: &str) -> String {
// The last argument is the largest number of matches to replace.
s.replacen(old, new, 1)
}
tests/replace_test.rs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/replace-a-substring/.
use algo_replace_a_substring::{replace, replace_first};
// U+0301 is COMBINING ACUTE ACCENT, and U+00E9 is the precomposed é.
#[test]
fn all() {
let cases = [
("all", "a-b-c", "-", "+", "a+b+c"),
("word", "Hello, world", "world", "there", "Hello, there"),
("none", "abc", "x", "y", "abc"),
("empty-s", "", "a", "b", ""),
("delete", "a-b-c", "-", "", "abc"),
("new-contains-old", "aXa", "X", "XXX", "aXXXa"),
("overlap", "aaaa", "aa", "b", "bb"),
("overlap-odd", "aaa", "aa", "b", "ba"),
("case-sensitive", "Hello hello", "hello", "bye", "Hello bye"),
("non-ascii", "naïve caf\u{e9}", "\u{e9}", "e", "naïve cafe"),
("astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "!", "a!b!"),
("combining", "cafe\u{301}", "e", "E", "cafE\u{301}"),
("precomposed", "caf\u{e9}", "e", "E", "caf\u{e9}"),
("dot", "a.b.c", ".", "-", "a-b-c"),
("dollar", "price", "price", "$&!", "$&!"),
("ampersand", "a-b", "-", "&", "a&b"),
("backslash", "a/b", "/", "\\", "a\\b"),
];
for (name, s, old, new, want) in cases {
assert_eq!(replace(s, old, new), want, "{name}");
}
}
#[test]
fn first() {
let cases = [
("first-only", "a-b-c", "-", "+", "a+b-c"),
("first-none", "abc", "x", "y", "abc"),
("first-overlap", "aaa", "aa", "b", "ba"),
("first-astral", "\u{1f642}\u{1f642}", "\u{1f642}", "x", "x\u{1f642}"),
("first-dollar", "a.b", ".", "$&", "a$&b"),
];
for (name, s, old, new, want) in cases {
assert_eq!(replace_first(s, old, new), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-a-substring/.
# replace S OLD NEW: prints S with each match of OLD replaced by NEW. The
# quotes around "$2" make OLD a literal string, not a pattern. Bash 5.2 replaces
# an unquoted & in NEW with the match when the option patsub_replacement is on,
# and Bash 3.2 keeps quotes in NEW as text. So the function turns the option
# off in a subshell and leaves NEW unquoted, which works in both.
replace() {
(
shopt -u patsub_replacement 2>/dev/null
local new=$3
printf '%s' "${1//"$2"/$new}"
)
}
# replace_first S OLD NEW: prints S with the first match of OLD replaced by NEW.
replace_first() {
(
shopt -u patsub_replacement 2>/dev/null
local new=$3
printf '%s' "${1/"$2"/$new}"
)
}
test_replace.bats 38 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/replace-a-substring/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/replace.sh"
}
check() { # check WANT FUNCTION S OLD NEW
run "$2" "$3" "$4" "$5"
[ "$status" -eq 0 ]
[ "$output" = "$1" ]
}
# CC 81 is U+0301 COMBINING ACUTE ACCENT, and C3 A9 is U+00E9.
@test "all" { check 'a+b+c' replace 'a-b-c' '-' '+'; }
@test "word" { check 'Hello, there' replace 'Hello, world' 'world' 'there'; }
@test "none" { check 'abc' replace 'abc' 'x' 'y'; }
@test "empty-s" { check '' replace '' 'a' 'b'; }
@test "delete" { check 'abc' replace 'a-b-c' '-' ''; }
@test "new-contains-old" { check 'aXXXa' replace 'aXa' 'X' 'XXX'; }
@test "overlap" { check 'bb' replace 'aaaa' 'aa' 'b'; }
@test "overlap-odd" { check 'ba' replace 'aaa' 'aa' 'b'; }
@test "case-sensitive" { check 'Hello bye' replace 'Hello hello' 'hello' 'bye'; }
@test "non-ascii" { check 'naïve cafe' replace $'naïve caf\xc3\xa9' $'\xc3\xa9' 'e'; }
@test "astral" { check 'a!b!' replace $'a\xf0\x9f\x99\x82b\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x82' '!'; }
@test "combining" { check $'cafE\xcc\x81' replace $'cafe\xcc\x81' 'e' 'E'; }
@test "precomposed" { check $'caf\xc3\xa9' replace $'caf\xc3\xa9' 'e' 'E'; }
@test "dot" { check 'a-b-c' replace 'a.b.c' '.' '-'; }
@test "dollar" { check '$&!' replace 'price' 'price' '$&!'; }
@test "ampersand" { check 'a&b' replace 'a-b' '-' '&'; }
@test "backslash" { check $'a\\b' replace 'a/b' '/' $'\\'; }
@test "first-only" { check 'a+b-c' replace_first 'a-b-c' '-' '+'; }
@test "first-none" { check 'abc' replace_first 'abc' 'x' 'y'; }
@test "first-overlap" { check 'ba' replace_first 'aaa' 'aa' 'b'; }
@test "first-astral" { check $'x\xf0\x9f\x99\x82' replace_first $'\xf0\x9f\x99\x82\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x82' 'x'; }
@test "first-dollar" { check 'a$&b' replace_first 'a.b' '.' '$&'; }
References
- The Python Standard Library, Built-in Types, str.replace; Text Sequence Type
- MDN Web Docs, String.prototype.replace(), Description; Specifying a string as the replacement; Specifying a function as the replacement
- Java SE 25 API, java.lang.String, replace(CharSequence, CharSequence); replaceAll; replaceFirst
- .NET API reference, String.Replace method, Replace(String, String)
- Go standard library, package strings, Replace, ReplaceAll
- The Rust Standard Library, primitive type str, replace, replacen
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Shell Parameter Expansion; Pattern Matching
- MDN Web Docs, String.prototype.replaceAll(), Parameters
- cppreference.com, strchr
- cppreference.com, std::basic_string replace
- cppreference.com, std::ranges::replace
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 5S107Z Edit this page History Report an error Markdown