Taskintro
Trim white space
Also called trim, strip, trim a string, remove leading and trailing spaces, lstrip, rstrip, trimStart, trimEnd, TrimSpace.
Remove the white space at the start and at the end of a string, and know which characters each language counts as white space.
- Evidence
- Code in 10 languages
Task
Remove the white space at the start and at the end of a string. The function trim(s) removes it from both ends, and the function trim_start(s) removes it only from the start. The white space between other characters stays. For example, trim(" hello world\n") is hello world.
The white space is the 6 ASCII white space characters: space, tab (U+0009), line feed (U+000A), vertical tab (U+000B), form feed (U+000C) and carriage return (U+000D). This is the set of the C locale, and the same set as is_blank in Check whether a string is empty. The trim of the library in most languages also removes the white space of Unicode, such as the no-break space U+00A0, so the solutions give the set.
Solutions
| Language | Trim of the library | Trim of the 6 ASCII characters |
|---|---|---|
| Python | s.strip() |
s.strip(" \t\n\v\f\r") |
| JavaScript, TypeScript | s.trim() |
s.replace with a regular expression |
| Java | s.strip() |
a loop from each end |
| C# | s.Trim() |
s.Trim(space) with an array of 6 chars |
| Go | strings.TrimSpace(s) |
strings.Trim(s, space) |
| Rust | s.trim() |
s.trim_matches(is_space) |
| C | none | a loop from each end, then a copy |
| C++ | none | find_first_not_of and find_last_not_of |
| Bash | none | two pattern removals with [![:space:]] |
- Python.
str.stripreturns "a copy of the string with the leading and trailing characters removed"1. With an argument, it removes each character of the argument. - JavaScript and TypeScript.
trim"removes whitespace from both ends of this string and returns a new string, without modifying the original string"2. The regular expression has the 6 characters. - Java. The loop finds the first and the last char that is not white space, and
substringreturns the text between them. - C#.
Trim(Char[])removes "all leading and trailing occurrences of a set of characters specified in an array from the current string"3. - Go.
strings.Trimtakes a cutset, and it removes each code point of the cutset from both ends. - Rust.
trim_matchestakes a function.trimreturns a slice of the same string, so it does not copy. - C. The code moves a pointer over the white space at the start, and it makes the length smaller for the white space at the end. Then it copies the text to a new string.
- C++.
find_first_not_ofandfind_last_not_offind the first and the last char that is not white space. - Bash.
${s%%[![:space:]]*}is the white space at the start, and${s#...}removes it. In the C locale, the classspaceis the 6 characters.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of trim_start are in cases/start.jsonl.
emptyandall-space: the result is the empty string.vt-ff: the vertical tab and the form feed are white space, so they are removed.other-control: U+0001 is a control character, but it is not white space, so it stays.no-break-space,ideographic-space,next-lineandbom: U+00A0, U+3000, U+0085 and U+FEFF stay. The trim of the library removes some of them, and it is different in each language.astral: an emoji between two spaces stays.combining: U+0301 after a space stays. The trim removes the space, and the combining mark is then at the start of the string.start-end-only:trim_startkeeps the white space at the end.
Pitfalls
- Python strip takes a set of characters. The argument is not a prefix. "See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters"1. With no argument,
stripremoves U+00A0 and U+3000:
print("Arthur: three!".lstrip("Arthur: "))
print("Arthur: three!".removeprefix("Arthur: "))
print(len("\u00a0x\u3000".strip()))
ee!
three!
1
- JavaScript trim removes more than ASCII. "Whitespace is defined as white space characters plus line terminators"2. The output shows that
trimremoves U+00A0, U+FEFF and U+3000:
console.log("\u00a0\ufeffx\u3000".trim().length);
console.log(JSON.stringify(" x ".trimStart()));
1
"x "
- Java trim and strip use different sets.
trimremoves each character "whose codepoint is less than or equal to 'U+0020' (the space character)"4, so it removes U+0001 and keeps U+3000.stripremoves "all leading and trailing white space"4, and the output shows that it keeps U+00A0:
public class Main {
public static void main(String[] args) {
System.out.println("\u0001x\u0001".trim().length());
System.out.println("\u3000x\u3000".trim().length());
System.out.println("\u3000x\u3000".strip().length());
System.out.println("\u00a0x\u00a0".strip().length());
}
}
1
3
1
3
- C# Trim() uses the white space of Unicode.
Trim()removes "all leading and trailing white-space characters from the current string"3, and it removes U+00A0.Trim('a', 'b')removes a set, not a word:
using System;
Console.WriteLine("\u00a0x\u00a0".Trim().Length);
Console.WriteLine("abcab".Trim('a', 'b'));
1
c
- Go TrimLeft is not TrimPrefix.
TrimLeftremoves each code point of the cutset. "To remove a prefix, use TrimPrefix instead"5.TrimSpaceremoves the white space "as defined by Unicode"5:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimLeft("abacus", "ab"))
fmt.Println(strings.TrimPrefix("abacus", "ab"))
fmt.Println(len(strings.TrimSpace("\u00a0x\u0085")))
}
cus
acus
1
- Rust is_ascii_whitespace does not include the vertical tab. "Because the list above excludes U+000B VERTICAL TAB, c.is_ascii_whitespace() is not equivalent to c.is_ascii() && c.is_whitespace()"6.
trimuses the property White_Space, "which includes newlines"7, and it removes U+000B:
fn main() {
let s = "\x0bhi\x0b";
println!("{}", s.trim().len());
println!("{}", s.trim_matches(|c: char| c.is_ascii_whitespace()).len());
}
2
4
- C isspace takes an unsigned char value. "The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF"8. To trim in place, keep the pointer to the start of the array, and move the text with
memmove, because the two ranges overlap:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = " hi ";
char *p = s;
while (isspace((unsigned char)*p)) {
p++;
}
size_t n = strlen(p);
while (n > 0 && isspace((unsigned char)p[n - 1])) {
n--;
}
memmove(s, p, n);
s[n] = '\0';
printf("[%s]\n", s);
return 0;
}
[hi]
- C++ find_first_not_of can return npos. "If all characters in the range can be found in the given character sequence, npos will be returned"9. For a string of only white space,
substr(npos)throwsstd::out_of_range, so check fornposfirst:
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string s = " ";
std::size_t start = s.find_first_not_of(" \t\n\v\f\r");
std::cout << (start == std::string::npos) << "\n";
try {
std::cout << s.substr(start) << "\n";
} catch (const std::out_of_range &) {
std::cout << "out_of_range\n";
}
}
1
out_of_range
- Bash
${s## }removes one space. The pattern is one space, and the expansion deletes "the longest matching pattern (the ‘##’ case)"10, which is still one space. A pattern with[![:space:]]finds all of the white space:
s=' hi '
echo "[${s## }]"
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
echo "[$s]"
[ hi ]
[hi]
Related tasks
- Check whether a string is empty: a string that is empty after a trim is blank.
- Split a string: trim each field after a split.
- Remove characters from a string: remove a character from each position, not only from the ends.
- Get a substring: the trim returns the substring between the first and the last other character.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/trim-whitespace/.
"""Trim the ASCII white space from a string."""
# The 6 ASCII white space characters. str.strip() with no argument also
# removes U+00A0, U+3000 and the other white space of Unicode.
WHITESPACE = " \t\n\v\f\r"
def trim(s: str) -> str:
"""Return s with the white space at the start and at the end removed."""
return s.strip(WHITESPACE)
def trim_start(s: str) -> str:
"""Return s with the white space at the start removed."""
return s.lstrip(WHITESPACE)
test_trim.py 43 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/trim-whitespace/.
import pytest
from trim import trim_start, trim
# The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
CASES = {
"both-ends": (" hello ", "hello"),
"tab-newline": ("\thello world\n", "hello world"),
"none": ("hello", "hello"),
"empty": ("", ""),
"all-space": (" \t\n\r ", ""),
"vt-ff": ("\v\fx\f\v", "x"),
"other-control": ("\u0001x\u0001", "\u0001x\u0001"),
"no-break-space": ("\u00a0x\u00a0", "\u00a0x\u00a0"),
"ideographic-space": ("\u3000x\u3000", "\u3000x\u3000"),
"next-line": ("\u0085x\u0085", "\u0085x\u0085"),
"bom": ("\ufeffx", "\ufeffx"),
"astral": (" \U0001f642 ", "\U0001f642"),
"combining": (" \u0301x ", "\u0301x"),
}
START = {
"start-both-ends": (" hello ", "hello "),
"start-tab-newline": ("\n\tx", "x"),
"start-empty": ("", ""),
"start-all-space": (" ", ""),
"start-no-break-space": ("\u00a0 x", "\u00a0 x"),
"start-end-only": ("x \t", "x \t"),
}
@pytest.mark.parametrize("name", CASES)
def test_trim(name):
s, want = CASES[name]
assert trim(s) == want
@pytest.mark.parametrize("name", START)
def test_trim_start(name):
s, want = START[name]
assert trim_start(s) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#include "trim.hpp"
namespace {
constexpr std::string_view space = " \t\n\v\f\r";
}
// find_first_not_of returns npos if each char is white space, so the function
// checks it before the call of find_last_not_of.
std::string trim(std::string_view s) {
std::size_t start = s.find_first_not_of(space);
if (start == std::string_view::npos) {
return {};
}
std::size_t end = s.find_last_not_of(space);
return std::string(s.substr(start, end - start + 1));
}
std::string trim_start(std::string_view s) {
std::size_t start = s.find_first_not_of(space);
if (start == std::string_view::npos) {
return {};
}
return std::string(s.substr(start));
}
trim.hpp 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#ifndef TRIM_HPP
#define TRIM_HPP
#include <string>
#include <string_view>
// trim returns s with the ASCII white space at the start and at the end
// removed.
std::string trim(std::string_view s);
// trim_start returns s with the white space at the start removed.
std::string trim_start(std::string_view s);
#endif
test_trim.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#include "trim.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++;
}
}
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
int main() {
check("both-ends", trim(" hello "), "hello");
check("tab-newline", trim("\thello world\n"), "hello world");
check("none", trim("hello"), "hello");
check("empty", trim(""), "");
check("all-space", trim(" \t\n\r "), "");
check("vt-ff", trim("\v\fx\f\v"), "x");
check("other-control", trim("\x01x\x01"), "\x01x\x01");
check("no-break-space", trim("\xc2\xa0x\xc2\xa0"), "\xc2\xa0x\xc2\xa0");
check("ideographic-space", trim("\xe3\x80\x80x\xe3\x80\x80"), "\xe3\x80\x80x\xe3\x80\x80");
check("next-line", trim("\xc2\x85x\xc2\x85"), "\xc2\x85x\xc2\x85");
check("bom", trim("\xef\xbb\xbfx"), "\xef\xbb\xbfx");
check("astral", trim(" \xf0\x9f\x99\x82 "), "\xf0\x9f\x99\x82");
check("combining", trim(" \xcc\x81x "), "\xcc\x81x");
check("start-both-ends", trim_start(" hello "), "hello ");
check("start-tab-newline", trim_start("\n\tx"), "x");
check("start-empty", trim_start(""), "");
check("start-all-space", trim_start(" "), "");
check("start-no-break-space", trim_start("\xc2\xa0 x"), "\xc2\xa0 x");
check("start-end-only", trim_start("x \t"), "x \t");
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
/** Trims the ASCII white space from a string. */
public final class Trim {
private Trim() {}
// trim() removes each char up to U+0020, and strip() removes the white space
// of Character.isWhitespace, so the class uses its own set.
private static boolean isSpace(char c) {
return c == ' ' || (c >= '\t' && c <= '\r');
}
/** Returns s with the white space at the start and at the end removed. */
public static String trim(String s) {
int start = 0;
int end = s.length();
while (start < end && isSpace(s.charAt(start))) {
start++;
}
while (end > start && isSpace(s.charAt(end - 1))) {
end--;
}
return s.substring(start, end);
}
/** Returns s with the white space at the start removed. */
public static String trimStart(String s) {
int start = 0;
while (start < s.length() && isSpace(s.charAt(start))) {
start++;
}
return s.substring(start);
}
}
TrimTest.java 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
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 TrimTest {
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("both-ends", " hello ", "hello"),
Arguments.of("tab-newline", "\thello world\n", "hello world"),
Arguments.of("none", "hello", "hello"),
Arguments.of("empty", "", ""),
Arguments.of("all-space", " \t\n\r ", ""),
Arguments.of("vt-ff", "\u000b\fx\f\u000b", "x"),
Arguments.of("other-control", "\u0001x\u0001", "\u0001x\u0001"),
Arguments.of("no-break-space", "\u00a0x\u00a0", "\u00a0x\u00a0"),
Arguments.of("ideographic-space", "\u3000x\u3000", "\u3000x\u3000"),
Arguments.of("next-line", "\u0085x\u0085", "\u0085x\u0085"),
Arguments.of("bom", "\ufeffx", "\ufeffx"),
Arguments.of("astral", " \ud83d\ude42 ", "\ud83d\ude42"),
Arguments.of("combining", " \u0301x ", "\u0301x"));
}
static Stream<Arguments> start() {
return Stream.of(
Arguments.of("start-both-ends", " hello ", "hello "),
Arguments.of("start-tab-newline", "\n\tx", "x"),
Arguments.of("start-empty", "", ""),
Arguments.of("start-all-space", " ", ""),
Arguments.of("start-no-break-space", "\u00a0 x", "\u00a0 x"),
Arguments.of("start-end-only", "x \t", "x \t"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void trim(String name, String s, String want) {
assertEquals(want, Trim.trim(s));
}
@ParameterizedTest(name = "{0}")
@MethodSource("start")
void trimStart(String name, String s, String want) {
assertEquals(want, Trim.trimStart(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#include "trim.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
// isspace depends on the locale, so the function gives the 6 ASCII
// characters. A byte of a UTF-8 sequence is 0x80 or more, so it is not white
// space.
static bool is_space(char c) { return c == ' ' || (c >= '\t' && c <= '\r'); }
static char *copy(const char *start, size_t n) {
char *out = malloc(n + 1);
if (out == NULL) {
return NULL;
}
memcpy(out, start, n);
out[n] = '\0';
return out;
}
char *trim(const char *s) {
while (is_space(*s)) {
s++;
}
size_t n = strlen(s);
while (n > 0 && is_space(s[n - 1])) {
n--;
}
return copy(s, n);
}
char *trim_start(const char *s) {
while (is_space(*s)) {
s++;
}
return copy(s, strlen(s));
}
trim.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#ifndef TRIM_H
#define TRIM_H
// trim returns a new string with the ASCII white space at the start and at the
// end of s removed, or NULL if there is no memory. The caller frees the result.
char *trim(const char *s);
// trim_start returns a new string with the white space at the start removed,
// or NULL if there is no memory. The caller frees the result.
char *trim_start(const char *s);
#endif
test_trim.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
#include "trim.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
// check frees got, which is a new string from trim or trim_start.
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);
}
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
int main(void) {
check("both-ends", trim(" hello "), "hello");
check("tab-newline", trim("\thello world\n"), "hello world");
check("none", trim("hello"), "hello");
check("empty", trim(""), "");
check("all-space", trim(" \t\n\r "), "");
check("vt-ff", trim("\v\fx\f\v"), "x");
check("other-control", trim("\x01x\x01"), "\x01x\x01");
check("no-break-space", trim("\xc2\xa0x\xc2\xa0"), "\xc2\xa0x\xc2\xa0");
check("ideographic-space", trim("\xe3\x80\x80x\xe3\x80\x80"), "\xe3\x80\x80x\xe3\x80\x80");
check("next-line", trim("\xc2\x85x\xc2\x85"), "\xc2\x85x\xc2\x85");
check("bom", trim("\xef\xbb\xbfx"), "\xef\xbb\xbfx");
check("astral", trim(" \xf0\x9f\x99\x82 "), "\xf0\x9f\x99\x82");
check("combining", trim(" \xcc\x81x "), "\xcc\x81x");
check("start-both-ends", trim_start(" hello "), "hello ");
check("start-tab-newline", trim_start("\n\tx"), "x");
check("start-empty", trim_start(""), "");
check("start-all-space", trim_start(" "), "");
check("start-no-break-space", trim_start("\xc2\xa0 x"), "\xc2\xa0 x");
check("start-end-only", trim_start("x \t"), "x \t");
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
/// <summary>Trims the ASCII white space from a string.</summary>
public static class AsciiTrim
{
// Trim() with no argument removes each char of Char.IsWhiteSpace, which
// includes U+00A0 and U+3000, so the class gives the 6 ASCII characters.
private static readonly char[] Space = { ' ', '\t', '\n', '\v', '\f', '\r' };
/// <summary>Returns s with the white space at the start and at the end removed.</summary>
public static string Trim(string s) => s.Trim(Space);
/// <summary>Returns s with the white space at the start removed.</summary>
public static string TrimStart(string s) => s.TrimStart(Space);
}
TrimTests.cs 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
using Xunit;
public sealed class TrimTests
{
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
public static TheoryData<string, string, string> Upper => new()
{
{ "both-ends", " hello ", "hello" },
{ "tab-newline", "\thello world\n", "hello world" },
{ "none", "hello", "hello" },
{ "empty", "", "" },
{ "all-space", " \t\n\r ", "" },
{ "vt-ff", "\v\fx\f\v", "x" },
{ "other-control", "\u0001x\u0001", "\u0001x\u0001" },
{ "no-break-space", "\u00a0x\u00a0", "\u00a0x\u00a0" },
{ "ideographic-space", "\u3000x\u3000", "\u3000x\u3000" },
{ "next-line", "\u0085x\u0085", "\u0085x\u0085" },
{ "bom", "\ufeffx", "\ufeffx" },
{ "astral", " \U0001f642 ", "\U0001f642" },
{ "combining", " \u0301x ", "\u0301x" },
};
public static TheoryData<string, string, string> Lower => new()
{
{ "start-both-ends", " hello ", "hello " },
{ "start-tab-newline", "\n\tx", "x" },
{ "start-empty", "", "" },
{ "start-all-space", " ", "" },
{ "start-no-break-space", "\u00a0 x", "\u00a0 x" },
{ "start-end-only", "x \t", "x \t" },
};
[Theory]
[MemberData(nameof(Upper))]
public void Trim(string name, string s, string want)
{
Assert.NotNull(name);
Assert.Equal(want, AsciiTrim.Trim(s));
}
[Theory]
[MemberData(nameof(Lower))]
public void TrimStart(string name, string s, string want)
{
Assert.NotNull(name);
Assert.Equal(want, AsciiTrim.TrimStart(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
// trim returns s with the 6 ASCII white space characters removed from the
// start and the end. String.prototype.trim also removes U+00A0, U+3000, U+FEFF
// and the line terminators of Unicode, so the code uses a regular expression.
export function trim(s) {
return s.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
}
// trimStart returns s with the white space at the start removed.
export function trimStart(s) {
return s.replace(/^[ \t\n\v\f\r]+/, "");
}
trim.test.js 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { trimStart, trim } from "./trim.js";
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
const cases = [
["both-ends", " hello ", "hello"],
["tab-newline", "\thello world\n", "hello world"],
["none", "hello", "hello"],
["empty", "", ""],
["all-space", " \t\n\r ", ""],
["vt-ff", "\v\fx\f\v", "x"],
["other-control", "\u0001x\u0001", "\u0001x\u0001"],
["no-break-space", "\u00a0x\u00a0", "\u00a0x\u00a0"],
["ideographic-space", "\u3000x\u3000", "\u3000x\u3000"],
["next-line", "\u0085x\u0085", "\u0085x\u0085"],
["bom", "\ufeffx", "\ufeffx"],
["astral", " \u{1f642} ", "\u{1f642}"],
["combining", " \u0301x ", "\u0301x"],
];
const start = [
["start-both-ends", " hello ", "hello "],
["start-tab-newline", "\n\tx", "x"],
["start-empty", "", ""],
["start-all-space", " ", ""],
["start-no-break-space", "\u00a0 x", "\u00a0 x"],
["start-end-only", "x \t", "x \t"],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.equal(trim(s), want);
});
}
for (const [name, s, want] of start) {
test(name, () => {
assert.equal(trimStart(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
// trim returns s with the 6 ASCII white space characters removed from the
// start and the end. String.prototype.trim also removes U+00A0, U+3000, U+FEFF
// and the line terminators of Unicode, so the code uses a regular expression.
export function trim(s: string): string {
return s.replace(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/g, "");
}
// trimStart returns s with the white space at the start removed.
export function trimStart(s: string): string {
return s.replace(/^[ \t\n\v\f\r]+/, "");
}
trim.test.ts 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { trimStart, trim } from "./trim.ts";
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
const cases = [
["both-ends", " hello ", "hello"],
["tab-newline", "\thello world\n", "hello world"],
["none", "hello", "hello"],
["empty", "", ""],
["all-space", " \t\n\r ", ""],
["vt-ff", "\v\fx\f\v", "x"],
["other-control", "\u0001x\u0001", "\u0001x\u0001"],
["no-break-space", "\u00a0x\u00a0", "\u00a0x\u00a0"],
["ideographic-space", "\u3000x\u3000", "\u3000x\u3000"],
["next-line", "\u0085x\u0085", "\u0085x\u0085"],
["bom", "\ufeffx", "\ufeffx"],
["astral", " \u{1f642} ", "\u{1f642}"],
["combining", " \u0301x ", "\u0301x"],
];
const start = [
["start-both-ends", " hello ", "hello "],
["start-tab-newline", "\n\tx", "x"],
["start-empty", "", ""],
["start-all-space", " ", ""],
["start-no-break-space", "\u00a0 x", "\u00a0 x"],
["start-end-only", "x \t", "x \t"],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.equal(trim(s), want);
});
}
for (const [name, s, want] of start) {
test(name, () => {
assert.equal(trimStart(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
// Package asciitrim trims the ASCII white space from a string.
package asciitrim
import "strings"
// space is the 6 ASCII white space characters. strings.TrimSpace also removes
// the white space of Unicode, such as U+00A0 and U+0085.
const space = " \t\n\v\f\r"
// Trim returns s with the white space at the start and at the end removed.
func Trim(s string) string {
return strings.Trim(s, space)
}
// TrimStart returns s with the white space at the start removed.
func TrimStart(s string) string {
return strings.TrimLeft(s, space)
}
trim_test.go 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
package asciitrim
import "testing"
type trimCase struct {
name, s, want string
}
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
var cases = []trimCase{
{"both-ends", " hello ", "hello"},
{"tab-newline", "\thello world\n", "hello world"},
{"none", "hello", "hello"},
{"empty", "", ""},
{"all-space", " \t\n\r ", ""},
{"vt-ff", "\v\fx\f\v", "x"},
{"other-control", "\u0001x\u0001", "\u0001x\u0001"},
{"no-break-space", "\u00a0x\u00a0", "\u00a0x\u00a0"},
{"ideographic-space", "\u3000x\u3000", "\u3000x\u3000"},
{"next-line", "\u0085x\u0085", "\u0085x\u0085"},
{"bom", "\ufeffx", "\ufeffx"},
{"astral", " \U0001f642 ", "\U0001f642"},
{"combining", " \u0301x ", "\u0301x"},
}
var start = []trimCase{
{"start-both-ends", " hello ", "hello "},
{"start-tab-newline", "\n\tx", "x"},
{"start-empty", "", ""},
{"start-all-space", " ", ""},
{"start-no-break-space", "\u00a0 x", "\u00a0 x"},
{"start-end-only", "x \t", "x \t"},
}
func TestTrim(t *testing.T) {
for _, c := range cases {
if got := Trim(c.s); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestTrimStart(t *testing.T) {
for _, c := range start {
if got := TrimStart(c.s); 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/trim-whitespace/.
/// Reports whether c is one of the 6 ASCII white space characters.
/// char::is_ascii_whitespace does not include U+000B, and str::trim removes
/// the white space of Unicode, so the function gives the set.
fn is_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
}
/// Returns s with the white space at the start and at the end removed.
pub fn trim(s: &str) -> &str {
s.trim_matches(is_space)
}
/// Returns s with the white space at the start removed.
pub fn trim_start(s: &str) -> &str {
s.trim_start_matches(is_space)
}
tests/trim_test.rs 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/trim-whitespace/.
use algo_trim_whitespace::{trim_start, trim};
// The white space is the 6 ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. U+00A0, U+3000, U+0085 and U+FEFF stay.
#[test]
fn cases() {
let cases = [
("both-ends", " hello ", "hello"),
("tab-newline", "\thello world\n", "hello world"),
("none", "hello", "hello"),
("empty", "", ""),
("all-space", " \t\n\r ", ""),
("vt-ff", "\x0b\x0cx\x0c\x0b", "x"),
("other-control", "\u{1}x\u{1}", "\u{1}x\u{1}"),
("no-break-space", "\u{a0}x\u{a0}", "\u{a0}x\u{a0}"),
("ideographic-space", "\u{3000}x\u{3000}", "\u{3000}x\u{3000}"),
("next-line", "\u{85}x\u{85}", "\u{85}x\u{85}"),
("bom", "\u{feff}x", "\u{feff}x"),
("astral", " \u{1f642} ", "\u{1f642}"),
("combining", " \u{301}x ", "\u{301}x"),
];
for (name, s, want) in cases {
assert_eq!(trim(s), want, "{name}");
}
}
#[test]
fn start() {
let cases = [
("start-both-ends", " hello ", "hello "),
("start-tab-newline", "\n\tx", "x"),
("start-empty", "", ""),
("start-all-space", " ", ""),
("start-no-break-space", "\u{a0} x", "\u{a0} x"),
("start-end-only", "x \t", "x \t"),
];
for (name, s, want) in cases {
assert_eq!(trim_start(s), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/trim-whitespace/.
# trim S: prints S with the white space at the start and at the end removed.
# In the C locale, the class [:space:] is the 6 ASCII white space characters.
# The first expansion removes the longest prefix of white space, and the second
# removes the longest suffix.
trim() {
(
LC_ALL=C
s=$1
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
printf '%s' "$s"
)
}
# trim_start S: prints S with the white space at the start removed.
trim_start() {
(
LC_ALL=C
s=$1
s=${s#"${s%%[![:space:]]*}"}
printf '%s' "$s"
)
}
test_trim.bats 35 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/trim-whitespace/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/trim.sh"
}
check() { # check FUNCTION S WANT
run "$1" "$2"
[ "$status" -eq 0 ]
[ "$output" = "$3" ]
}
# Only the 6 ASCII white space bytes are removed, so each byte of 0x80 or more stays.
@test "both-ends" { check trim ' hello ' 'hello'; }
@test "tab-newline" { check trim $'\thello world\n' 'hello world'; }
@test "none" { check trim 'hello' 'hello'; }
@test "empty" { check trim '' ''; }
@test "all-space" { check trim $' \t\n\r ' ''; }
@test "vt-ff" { check trim $'\v\fx\f\v' 'x'; }
@test "other-control" { check trim $'\x01x\x01' $'\x01x\x01'; }
@test "no-break-space" { check trim $'\xc2\xa0x\xc2\xa0' $'\xc2\xa0x\xc2\xa0'; }
@test "ideographic-space" { check trim $'\xe3\x80\x80x\xe3\x80\x80' $'\xe3\x80\x80x\xe3\x80\x80'; }
@test "next-line" { check trim $'\xc2\x85x\xc2\x85' $'\xc2\x85x\xc2\x85'; }
@test "bom" { check trim $'\xef\xbb\xbfx' $'\xef\xbb\xbfx'; }
@test "astral" { check trim $' \xf0\x9f\x99\x82 ' $'\xf0\x9f\x99\x82'; }
@test "combining" { check trim $' \xcc\x81x ' $'\xcc\x81x'; }
@test "start-both-ends" { check trim_start ' hello ' 'hello '; }
@test "start-tab-newline" { check trim_start $'\n\tx' 'x'; }
@test "start-empty" { check trim_start '' ''; }
@test "start-all-space" { check trim_start ' ' ''; }
@test "start-no-break-space" { check trim_start $'\xc2\xa0 x' $'\xc2\xa0 x'; }
@test "start-end-only" { check trim_start $'x \t' $'x \t'; }
References
- The Python Standard Library, Built-in Types, str.strip, str.lstrip
- MDN Web Docs, String.prototype.trim(), Description
- .NET API reference, String.Trim method, Overloads
- Java SE 25 API, Class String, trim(), strip()
- Go standard library, package strings, TrimSpace, TrimLeft
- Rust standard library, primitive type char, is_ascii_whitespace
- Rust standard library, primitive type str, trim
- cppreference.com, isspace, Description
- cppreference.com, std::basic_string::find_first_not_of, Description
- Bash Reference Manual, 3.5.3 Shell Parameter Expansion, 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.
| 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 HYHEK1 Edit this page History Report an error Markdown