Programming Search⌘K

Taskintro

Remove characters from a string

Also called delete characters, strip characters, remove a character, filter characters, remove all occurrences, translate, retain.

Remove each character of a set from a string, and remove whole code points, not bytes or UTF-16 code units.

Task

Remove each character of a set from a string. The function remove_chars(s, chars) returns s without each code point that is also in chars. The other code points stay in the same order. For example, remove_chars("banana", "a") is bnn, and remove_chars("hello, world", "lo") is he, wrd.

A character is a code point. An emoji above U+FFFF is one character, and a combining mark such as U+0301 is a character of its own. The code must not remove a part of a code point: one UTF-16 code unit of a surrogate pair, or one byte of a UTF-8 sequence.

Solutions

Language Remove the code points of a set
Python s.translate(str.maketrans("", "", chars))
JavaScript, TypeScript Array.from(s).filter with a Set of chars
Java s.codePoints().filter and appendCodePoint
C# EnumerateRunes and a HashSet<Rune>
Go strings.Map that returns -1 for a rune of chars
Rust s.chars().filter(...).collect()
C a loop over the UTF-8 sequences, and memcmp with each sequence of chars
C++ the same loop, with std::string_view
Bash ${s//"$c"/} for each code point c of chars
  • Python. For str.maketrans, "If there is a third argument, it must be a string, whose characters will be mapped to None in the result"1. translate removes each character that maps to None.
  • JavaScript and TypeScript. Array.from and new Set use the iterator of a string, which gives code points. So a code point above U+FFFF is one element.
  • Java. codePoints() gives the code points as an IntStream. indexOf(int) finds a code point above U+FFFF in chars.
  • C#. A Rune is one code point. A surrogate pair is one Rune.
  • Go. "If mapping returns a negative value, the character is dropped from the string with no replacement"2.
  • Rust. chars() gives each char, which is a code point. To change a String in place, use retain, which keeps "only the characters specified by the predicate"3.
  • C and C++. The first byte of a UTF-8 sequence gives its length: 1 byte below 0x80, 2 bytes from 0xC0, 3 bytes from 0xE0 and 4 bytes from 0xF0. The loop compares whole sequences.
  • Bash. In the C locale, the loop takes the bytes of each code point of chars from the first byte. The quotes in "$c" make it a plain string, not a pattern.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty and empty-set: an empty string stays empty, and an empty set removes nothing.
  • none-found and all: if no character is in the set, the string does not change, and if each character is in the set, the result is empty.
  • adjacent: in aab, the two a characters are next to each other, and both are removed.
  • astral and astral-other: U+1F642 and U+1F643 have the same high surrogate in UTF-16. The removal of U+1F643 must keep U+1F642.
  • non-ascii: à (U+00E0) and é (U+00E9) have the same first byte 0xC3 in UTF-8. The removal of é must keep à.
  • combining-mark and combining-base: the removal of U+0301 from e and U+0301 leaves e. The removal of e leaves U+0301 alone.
  • composed: é as one code point is not e and U+0301, so it removes nothing. See Normalize Unicode text.

Pitfalls

  • Python strip removes only the ends. strip("-") removes the - at the ends, and it keeps the others. Use translate, or replace for one character:
s = "a-b-c-"
print(s.strip("-"))
print(s.translate(str.maketrans("", "", "-")))
print(s.replace("-", ""))
Output
a-b-c
abc
abc
  • JavaScript replace with a string removes only the first match. "If pattern is a string, only the first occurrence will be replaced"4. Use replaceAll. Also, split("") gives UTF-16 code units, so it cuts an emoji in two:
console.log("a-b-c".replace("-", ""));
console.log("a-b-c".replaceAll("-", ""));
console.log("\u{1f642}".split("").length, Array.from("\u{1f642}").length);
Output
ab-c
abc
2 1
  • Java deleteCharAt in a loop skips a char. After a removal, the next char moves to the same index, and i++ skips it. Go from the end to the start. Also, "If the character at the given index is a supplementary character, this method does not remove the entire character"5:
public class Main {
  public static void main(String[] args) {
    StringBuilder up = new StringBuilder("aab");
    for (int i = 0; i < up.length(); i++) {
      if (up.charAt(i) == 'a') {
        up.deleteCharAt(i);
      }
    }
    System.out.println(up);
    StringBuilder down = new StringBuilder("aab");
    for (int i = down.length() - 1; i >= 0; i--) {
      if (down.charAt(i) == 'a') {
        down.deleteCharAt(i);
      }
    }
    System.out.println(down);
  }
}
Output
ab
b
  • C# Remove(int) removes the end of the string. Remove(1) returns "a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted"6. To remove one character at an index, use Remove(i, 1). To remove each copy of a character, use Replace:
using System;

Console.WriteLine("hello".Remove(1));
Console.WriteLine("hello".Remove(1, 1));
Console.WriteLine("hello".Replace("l", ""));
Output
h
hllo
heo
  • Go strings.IndexByte compares bytes. A loop over the bytes of s removes each byte of é, and it removes the first byte of à too. The result is not valid UTF-8. strings.Map removes whole runes:
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	s, chars := "\u00e0\u00e9", "\u00e9"
	var b []byte
	for i := 0; i < len(s); i++ {
		if strings.IndexByte(chars, s[i]) < 0 {
			b = append(b, s[i])
		}
	}
	fmt.Println(len(b), utf8.Valid(b))
	r := strings.Map(func(r rune) rune {
		if strings.ContainsRune(chars, r) {
			return -1
		}
		return r
	}, s)
	fmt.Printf("%U\n", []rune(r))
}
Output
1 false
[U+00E0]
  • Rust String::remove takes a byte index. It "Panics if idx is larger than or equal to the String’s length, or if it does not lie on a char boundary"3. Byte 1 of é is in the middle of the char. Use retain to remove each match:
fn main() {
    let mut s = String::from("e\u{301}x");
    s.retain(|c| c != '\u{301}');
    println!("{s}");
    let t = String::from("\u{e9}x");
    println!("{}", t.is_char_boundary(1));
}
Output
ex
false
  • C strchr compares bytes. With chars set to é, the loop removes the bytes 0xC3 and 0xA9. It also removes the first byte of à, and only 0xA0 stays:
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "\xc3\xa0\xc3\xa9";
    const char *chars = "\xc3\xa9";
    for (const char *p = s; *p != '\0'; p++) {
        if (strchr(chars, *p) == NULL) {
            printf("%02x\n", (unsigned char)*p);
        }
    }
    return 0;
}
Output
a0
  • C++ std::remove does not change the size. "A call to remove or remove_if is typically followed by a call to a container's erase member function to actually remove elements from the container"7. In C++20 and later, std::erase does both:
#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string s = "banana";
    auto end = std::remove(s.begin(), s.end(), 'a');
    std::cout << s.size() << " " << (end - s.begin()) << "\n";
    s.erase(end, s.end());
    std::cout << s << "\n";
    std::string t = "banana";
    std::erase(t, 'n');
    std::cout << t << "\n";
}
Output
6 3
bnn
baaa
  • Bash [$chars] is a pattern. "If the first character following the ‘[’ is a ‘!’ or a ‘^’ then any character not within the range matches"8. If chars starts with !, the pattern removes each other character:
s='banana!'
chars='!a'
echo "${s//[$chars]/}"
echo "${s//[a!]/}"
Output
aaa
bnn

Code

The build runs the native tests of each language in a pinned toolchain.

remove.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-characters-from-a-string/.

"""Remove each code point of a set from a string."""


def remove_chars(s: str, chars: str) -> str:
    """Return s without the code points of chars.

    A str is a sequence of code points, and the third argument of
    str.maketrans maps each of its code points to None, so translate
    removes them.
    """
    return s.translate(str.maketrans("", "", chars))
test_remove.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-characters-from-a-string/.

import pytest

from remove import remove_chars

# A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
CASES = {
    "one-char": ("banana", "a", "bnn"),
    "set": ("hello, world", "lo", "he, wrd"),
    "punct": ("a-b_c.d", "-_.", "abcd"),
    "empty": ("", "abc", ""),
    "empty-set": ("hello", "", "hello"),
    "none-found": ("hello", "xyz", "hello"),
    "all": ("aaa", "a", ""),
    "adjacent": ("aab", "a", "b"),
    "astral": ("a\U0001f642b\U0001f642", "\U0001f642", "ab"),
    "astral-other": ("\U0001f642\U0001f643", "\U0001f643", "\U0001f642"),
    "non-ascii": ("\u00e0\u00e9", "\u00e9", "\u00e0"),
    "combining-mark": ("e\u0301x", "\u0301", "ex"),
    "combining-base": ("e\u0301", "e", "\u0301"),
    "composed": ("e\u0301", "\u00e9", "e\u0301"),
}


@pytest.mark.parametrize("name", CASES)
def test_remove_chars(name):
    s, chars, want = CASES[name]
    assert remove_chars(s, chars) == want
remove.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#include "remove.hpp"

#include <cstddef>
#include <vector>

namespace {

// seq_len returns the length of the UTF-8 sequence that starts with the byte b.
std::size_t seq_len(unsigned char b) {
    return b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
}

// split returns the code points of s, each as the view of its bytes.
std::vector<std::string_view> split(std::string_view s) {
    std::vector<std::string_view> out;
    for (std::size_t i = 0; i < s.size();) {
        std::size_t n = seq_len(static_cast<unsigned char>(s[i]));
        out.push_back(s.substr(i, n));
        i += n;
    }
    return out;
}

}  // namespace

// The function compares whole UTF-8 sequences. A compare of single bytes, as
// with find_first_of, would remove a part of a multibyte sequence.
std::string remove_chars(std::string_view s, std::string_view chars) {
    std::vector<std::string_view> remove = split(chars);
    std::string out;
    out.reserve(s.size());
    for (std::string_view c : split(s)) {
        bool found = false;
        for (std::string_view r : remove) {
            if (r == c) {
                found = true;
                break;
            }
        }
        if (!found) {
            out += c;
        }
    }
    return out;
}
remove.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#ifndef REMOVE_HPP
#define REMOVE_HPP

#include <string>
#include <string_view>

// remove_chars returns s with each code point of chars removed. s and chars are
// valid UTF-8.
std::string remove_chars(std::string_view s, std::string_view chars);

#endif
test_remove.cpp 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#include "remove.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++;
    }
}

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
int main() {
    check("one-char", remove_chars("banana", "a"), "bnn");
    check("set", remove_chars("hello, world", "lo"), "he, wrd");
    check("punct", remove_chars("a-b_c.d", "-_."), "abcd");
    check("empty", remove_chars("", "abc"), "");
    check("empty-set", remove_chars("hello", ""), "hello");
    check("none-found", remove_chars("hello", "xyz"), "hello");
    check("all", remove_chars("aaa", "a"), "");
    check("adjacent", remove_chars("aab", "a"), "b");
    check("astral", remove_chars("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), "ab");
    check("astral-other", remove_chars("\xf0\x9f\x99\x82\xf0\x9f\x99\x83", "\xf0\x9f\x99\x83"), "\xf0\x9f\x99\x82");
    check("non-ascii", remove_chars("\xc3\xa0\xc3\xa9", "\xc3\xa9"), "\xc3\xa0");
    check("combining-mark", remove_chars("e\xcc\x81x", "\xcc\x81"), "ex");
    check("combining-base", remove_chars("e\xcc\x81", "e"), "\xcc\x81");
    check("composed", remove_chars("e\xcc\x81", "\xc3\xa9"), "e\xcc\x81");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Remove.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

/** Removes each code point of a set from a string. */
public final class Remove {
  private Remove() {}

  /**
   * Returns s without the code points of chars. The loop uses code points, so a
   * surrogate pair is one character, and indexOf(int) finds a code point above
   * U+FFFF in chars.
   */
  public static String removeChars(String s, String chars) {
    StringBuilder sb = new StringBuilder(s.length());
    s.codePoints().filter(cp -> chars.indexOf(cp) < 0).forEach(sb::appendCodePoint);
    return sb.toString();
  }
}
RemoveTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

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 RemoveTest {
  // A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("one-char", "banana", "a", "bnn"),
        Arguments.of("set", "hello, world", "lo", "he, wrd"),
        Arguments.of("punct", "a-b_c.d", "-_.", "abcd"),
        Arguments.of("empty", "", "abc", ""),
        Arguments.of("empty-set", "hello", "", "hello"),
        Arguments.of("none-found", "hello", "xyz", "hello"),
        Arguments.of("all", "aaa", "a", ""),
        Arguments.of("adjacent", "aab", "a", "b"),
        Arguments.of("astral", "a\ud83d\ude42b\ud83d\ude42", "\ud83d\ude42", "ab"),
        Arguments.of("astral-other", "\ud83d\ude42\ud83d\ude43", "\ud83d\ude43", "\ud83d\ude42"),
        Arguments.of("non-ascii", "\u00e0\u00e9", "\u00e9", "\u00e0"),
        Arguments.of("combining-mark", "e\u0301x", "\u0301", "ex"),
        Arguments.of("combining-base", "e\u0301", "e", "\u0301"),
        Arguments.of("composed", "e\u0301", "\u00e9", "e\u0301"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void removeChars(String name, String s, String chars, String want) {
    assertEquals(want, Remove.removeChars(s, chars));
  }
}
remove.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#include "remove.h"

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

// seq_len returns the length of the UTF-8 sequence that starts with the byte b.
static size_t seq_len(unsigned char b) {
    if (b >= 0xf0) {
        return 4;
    }
    if (b >= 0xe0) {
        return 3;
    }
    if (b >= 0xc0) {
        return 2;
    }
    return 1;
}

// in_set reports whether the n bytes at p are one of the code points of chars.
// strchr would compare single bytes, and then it would remove a part of a
// multibyte sequence, so the loop compares whole sequences.
static bool in_set(const char *p, size_t n, const char *chars) {
    while (*chars != '\0') {
        size_t m = seq_len((unsigned char)*chars);
        if (m == n && memcmp(p, chars, n) == 0) {
            return true;
        }
        chars += m;
    }
    return false;
}

char *remove_chars(const char *s, const char *chars) {
    char *out = malloc(strlen(s) + 1);
    if (out == NULL) {
        return NULL;
    }
    size_t j = 0;
    while (*s != '\0') {
        size_t n = seq_len((unsigned char)*s);
        if (!in_set(s, n, chars)) {
            memcpy(out + j, s, n);
            j += n;
        }
        s += n;
    }
    out[j] = '\0';
    return out;
}
remove.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#ifndef REMOVE_H
#define REMOVE_H

// remove_chars returns a new string with each code point of chars removed from
// s, or NULL if there is no memory. s and chars are valid UTF-8. The caller
// frees the result.
char *remove_chars(const char *s, const char *chars);

#endif
test_remove.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

#include "remove.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

// check frees got, which is a new string from remove_chars.
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);
}

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
int main(void) {
    check("one-char", remove_chars("banana", "a"), "bnn");
    check("set", remove_chars("hello, world", "lo"), "he, wrd");
    check("punct", remove_chars("a-b_c.d", "-_."), "abcd");
    check("empty", remove_chars("", "abc"), "");
    check("empty-set", remove_chars("hello", ""), "hello");
    check("none-found", remove_chars("hello", "xyz"), "hello");
    check("all", remove_chars("aaa", "a"), "");
    check("adjacent", remove_chars("aab", "a"), "b");
    check("astral", remove_chars("a\xf0\x9f\x99\x82" "b\xf0\x9f\x99\x82", "\xf0\x9f\x99\x82"), "ab");
    check("astral-other", remove_chars("\xf0\x9f\x99\x82\xf0\x9f\x99\x83", "\xf0\x9f\x99\x83"), "\xf0\x9f\x99\x82");
    check("non-ascii", remove_chars("\xc3\xa0\xc3\xa9", "\xc3\xa9"), "\xc3\xa0");
    check("combining-mark", remove_chars("e\xcc\x81x", "\xcc\x81"), "ex");
    check("combining-base", remove_chars("e\xcc\x81", "e"), "\xcc\x81");
    check("composed", remove_chars("e\xcc\x81", "\xc3\xa9"), "e\xcc\x81");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CharRemover.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

using System.Collections.Generic;
using System.Text;

/// <summary>Removes each code point of a set from a string.</summary>
public static class CharRemover
{
    /// <summary>
    /// Returns s without the code points of chars. EnumerateRunes gives code
    /// points, so a surrogate pair is one Rune.
    /// </summary>
    public static string RemoveChars(string s, string chars)
    {
        var remove = new HashSet<Rune>(chars.EnumerateRunes());
        var sb = new StringBuilder(s.Length);
        foreach (Rune r in s.EnumerateRunes())
        {
            if (!remove.Contains(r))
            {
                sb.Append(r.ToString());
            }
        }
        return sb.ToString();
    }
}
RemoveTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

using Xunit;

public sealed class RemoveTests
{
    // A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
    public static TheoryData<string, string, string, string> Cases => new()
    {
        { "one-char", "banana", "a", "bnn" },
        { "set", "hello, world", "lo", "he, wrd" },
        { "punct", "a-b_c.d", "-_.", "abcd" },
        { "empty", "", "abc", "" },
        { "empty-set", "hello", "", "hello" },
        { "none-found", "hello", "xyz", "hello" },
        { "all", "aaa", "a", "" },
        { "adjacent", "aab", "a", "b" },
        { "astral", "a\U0001f642b\U0001f642", "\U0001f642", "ab" },
        { "astral-other", "\U0001f642\U0001f643", "\U0001f643", "\U0001f642" },
        { "non-ascii", "\u00e0\u00e9", "\u00e9", "\u00e0" },
        { "combining-mark", "e\u0301x", "\u0301", "ex" },
        { "combining-base", "e\u0301", "e", "\u0301" },
        { "composed", "e\u0301", "\u00e9", "e\u0301" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void RemoveChars(string name, string s, string chars, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, CharRemover.RemoveChars(s, chars));
    }
}
remove.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

// removeChars returns s without the code points of chars. The iterator of a
// string gives code points, not UTF-16 code units, so a code point above
// U+FFFF is one element of the Set and of the array.
export function removeChars(s, chars) {
  const remove = new Set(chars);
  return Array.from(s)
    .filter((c) => !remove.has(c))
    .join("");
}
remove.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { removeChars } from "./remove.js";

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
const cases = [
  ["one-char", "banana", "a", "bnn"],
  ["set", "hello, world", "lo", "he, wrd"],
  ["punct", "a-b_c.d", "-_.", "abcd"],
  ["empty", "", "abc", ""],
  ["empty-set", "hello", "", "hello"],
  ["none-found", "hello", "xyz", "hello"],
  ["all", "aaa", "a", ""],
  ["adjacent", "aab", "a", "b"],
  ["astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "ab"],
  ["astral-other", "\u{1f642}\u{1f643}", "\u{1f643}", "\u{1f642}"],
  ["non-ascii", "\u00e0\u00e9", "\u00e9", "\u00e0"],
  ["combining-mark", "e\u0301x", "\u0301", "ex"],
  ["combining-base", "e\u0301", "e", "\u0301"],
  ["composed", "e\u0301", "\u00e9", "e\u0301"],
];

for (const [name, s, chars, want] of cases) {
  test(name, () => {
    assert.equal(removeChars(s, chars), want);
  });
}
remove.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

// removeChars returns s without the code points of chars. The iterator of a
// string gives code points, not UTF-16 code units, so a code point above
// U+FFFF is one element of the Set and of the array.
export function removeChars(s: string, chars: string): string {
  const remove = new Set(chars);
  return Array.from(s)
    .filter((c) => !remove.has(c))
    .join("");
}
remove.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { removeChars } from "./remove.ts";

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
const cases: [string, string, string, string][] = [
  ["one-char", "banana", "a", "bnn"],
  ["set", "hello, world", "lo", "he, wrd"],
  ["punct", "a-b_c.d", "-_.", "abcd"],
  ["empty", "", "abc", ""],
  ["empty-set", "hello", "", "hello"],
  ["none-found", "hello", "xyz", "hello"],
  ["all", "aaa", "a", ""],
  ["adjacent", "aab", "a", "b"],
  ["astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "ab"],
  ["astral-other", "\u{1f642}\u{1f643}", "\u{1f643}", "\u{1f642}"],
  ["non-ascii", "\u00e0\u00e9", "\u00e9", "\u00e0"],
  ["combining-mark", "e\u0301x", "\u0301", "ex"],
  ["combining-base", "e\u0301", "e", "\u0301"],
  ["composed", "e\u0301", "\u00e9", "e\u0301"],
];

for (const [name, s, chars, want] of cases) {
  test(name, () => {
    assert.equal(removeChars(s, chars), want);
  });
}
remove.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

// Package remove removes each code point of a set from a string.
package remove

import "strings"

// RemoveChars returns s without the code points of chars. strings.Map drops
// a rune if the function returns a negative value.
func RemoveChars(s, chars string) string {
	return strings.Map(func(r rune) rune {
		if strings.ContainsRune(chars, r) {
			return -1
		}
		return r
	}, s)
}
remove_test.go 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

package remove

import "testing"

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
var cases = []struct {
	name, s, chars, want string
}{
	{"one-char", "banana", "a", "bnn"},
	{"set", "hello, world", "lo", "he, wrd"},
	{"punct", "a-b_c.d", "-_.", "abcd"},
	{"empty", "", "abc", ""},
	{"empty-set", "hello", "", "hello"},
	{"none-found", "hello", "xyz", "hello"},
	{"all", "aaa", "a", ""},
	{"adjacent", "aab", "a", "b"},
	{"astral", "a\U0001f642b\U0001f642", "\U0001f642", "ab"},
	{"astral-other", "\U0001f642\U0001f643", "\U0001f643", "\U0001f642"},
	{"non-ascii", "\u00e0\u00e9", "\u00e9", "\u00e0"},
	{"combining-mark", "e\u0301x", "\u0301", "ex"},
	{"combining-base", "e\u0301", "e", "\u0301"},
	{"composed", "e\u0301", "\u00e9", "e\u0301"},
}

func TestRemoveChars(t *testing.T) {
	for _, c := range cases {
		if got := RemoveChars(c.s, c.chars); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
remove.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

/// Returns s without the code points of chars. chars() gives each char, which
/// is a code point.
pub fn remove_chars(s: &str, chars: &str) -> String {
    s.chars().filter(|c| !chars.contains(*c)).collect()
}
tests/remove_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-characters-from-a-string/.

use algo_remove_characters_from_a_string::remove_chars;

// A character is a code point. U+1F642 and U+1F643 have the same high surrogate in UTF-16, and U+00E0 and U+00E9 have the same first byte in UTF-8.
#[test]
fn cases() {
    let cases: [(&str, &str, &str, &str); 14] = [
        ("one-char", "banana", "a", "bnn"),
        ("set", "hello, world", "lo", "he, wrd"),
        ("punct", "a-b_c.d", "-_.", "abcd"),
        ("empty", "", "abc", ""),
        ("empty-set", "hello", "", "hello"),
        ("none-found", "hello", "xyz", "hello"),
        ("all", "aaa", "a", ""),
        ("adjacent", "aab", "a", "b"),
        ("astral", "a\u{1f642}b\u{1f642}", "\u{1f642}", "ab"),
        ("astral-other", "\u{1f642}\u{1f643}", "\u{1f643}", "\u{1f642}"),
        ("non-ascii", "\u{e0}\u{e9}", "\u{e9}", "\u{e0}"),
        ("combining-mark", "e\u{301}x", "\u{301}", "ex"),
        ("combining-base", "e\u{301}", "e", "\u{301}"),
        ("composed", "e\u{301}", "\u{e9}", "e\u{301}"),
    ];
    for (name, s, chars, want) in cases {
        assert_eq!(remove_chars(s, chars), want, "{name}");
    }
}
remove.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-characters-from-a-string/.

# remove_chars S CHARS: prints S without the code points of CHARS. In the C
# locale, ${chars:i:1} is one byte, so the loop finds the length of each UTF-8
# sequence from its first byte. Then ${s//"$c"/} removes each copy of the whole
# sequence. The quotes make the sequence a plain string, not a pattern.
remove_chars() {
  (
    LC_ALL=C
    s=$1
    chars=$2
    i=0
    while ((i < ${#chars})); do
      b=${chars:i:1}
      n=1
      if [[ $b > $'\xef' ]]; then
        n=4
      elif [[ $b > $'\xdf' ]]; then
        n=3
      elif [[ $b > $'\x7f' ]]; then
        n=2
      fi
      c=${chars:i:n}
      s=${s//"$c"/}
      ((i += n))
    done
    printf '%s' "$s"
  )
}
test_remove.bats 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-characters-from-a-string/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/remove.sh"
}

check() { # check S CHARS WANT
  run remove_chars "$1" "$2"
  [ "$status" -eq 0 ]
  [ "$output" = "$3" ]
}

# Each argument is a string of UTF-8 bytes, and the function removes whole code points.
@test "one-char" { check 'banana' 'a' 'bnn'; }
@test "set" { check 'hello, world' 'lo' 'he, wrd'; }
@test "punct" { check 'a-b_c.d' '-_.' 'abcd'; }
@test "empty" { check '' 'abc' ''; }
@test "empty-set" { check 'hello' '' 'hello'; }
@test "none-found" { check 'hello' 'xyz' 'hello'; }
@test "all" { check 'aaa' 'a' ''; }
@test "adjacent" { check 'aab' 'a' 'b'; }
@test "astral" { check $'a\xf0\x9f\x99\x82b\xf0\x9f\x99\x82' $'\xf0\x9f\x99\x82' 'ab'; }
@test "astral-other" { check $'\xf0\x9f\x99\x82\xf0\x9f\x99\x83' $'\xf0\x9f\x99\x83' $'\xf0\x9f\x99\x82'; }
@test "non-ascii" { check $'\xc3\xa0\xc3\xa9' $'\xc3\xa9' $'\xc3\xa0'; }
@test "combining-mark" { check $'e\xcc\x81x' $'\xcc\x81' 'ex'; }
@test "combining-base" { check $'e\xcc\x81' 'e' $'\xcc\x81'; }
@test "composed" { check $'e\xcc\x81' $'\xc3\xa9' $'e\xcc\x81'; }

References

  1. The Python Standard Library, Built-in Types, str.maketrans, str.translate
  2. Go standard library, package strings, Map
  3. Rust standard library, struct String, retain, remove
  4. MDN Web Docs, String.prototype.replace(), Description
  5. Java SE 25 API, Class StringBuilder, deleteCharAt(int)
  6. .NET API reference, String.Remove method, Overloads
  7. cppreference.com, std::remove, std::remove_if, Notes
  8. Bash Reference Manual, 3.5.8.1 Pattern Matching

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source