Skip to content

str::trim_ascii

str methods · Strings

Level: reference · for working programmers

One line: trim restricted to the five ASCII whitespace bytes — and usable in a const context, which trim is not.

pub const fn trim_ascii(&self) -> &str

Stable since 1.80.0. Usable in a const context.

Removes only space, \t, \n, \r and form feed. A non-breaking space or any other Unicode space is left in place.

Two reasons to reach for it. It is const fn, so it can trim a literal at compile time — which trim cannot do, because Unicode whitespace classification is a table lookup. And it works byte-at-a-time, so it is faster on input you already know is ASCII.

The blindness is the cost: text pasted out of a word processor often carries U+00A0, and this will not remove it. When the input came from a human, use trim.

Example

str_trim_ascii.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let s = "  hello \t\n";
    println!("{:?}", s.trim_ascii());
    println!("{}", s.trim_ascii() == s.trim());

    // const: a literal trimmed at compile time.
    const RAW: &str = "  compiled  ";
    const TRIMMED: &str = RAW.trim_ascii();
    println!("{TRIMMED:?}");

    // Where they differ: a non-breaking space is not ASCII whitespace.
    let nbsp = "\u{00A0}hi\u{00A0}";
    println!("{:?} vs {:?}", nbsp.trim_ascii(), nbsp.trim());

    // The five bytes it does remove.
    println!("{:?}", " \t\n\r\u{000C}x \t\n\r\u{000C}".trim_ascii());
}

Verified output of str_trim_ascii.rs — regenerated by tools/run_examples.py, never hand-typed.

"hello"
true
"compiled"
"\u{a0}hi\u{a0}" vs "hi"
"x"

See also

str::trim_ascii in the standard library ↗

Po polsku

Wyróżnikiem tej metody nie jest to, co usuwa, tylko kiedy wolno jej to zrobić: jest const fn, więc const TRIMMED: &str = RAW.trim_ascii(); kompiluje się bez mrugnięcia okiem, a trim w tym samym miejscu nie przejdzie — unikodowa klasyfikacja białych znaków to zaglądanie do tablicy, czego w czasie kompilacji zrobić się nie da. Zdejmuje dokładnie pięć bajtów (spacja, \t, \n, \r, wysuw strony) i idzie po wejściu bajt po bajcie, więc na danych, o których z góry wiadomo, że są ASCII, jest zwyczajnie szybsza. Cenę tej ślepoty widać w wyjściu przykładu: "\u{a0}hi\u{a0}" wraca nietknięte, podczas gdy trim daje "hi" — a że tekst przeklejony z Worda albo ze strony WWW nagminnie niesie U+00A0, reguła wyboru jest prosta: dane maszynowe (literały, protokoły, pliki konfiguracyjne) trim_ascii, tekst od człowieka trim.

Szukaj po polsku: białe znaki ASCII · funkcje const w Ruscie · rust trim_ascii const fn · rust non-breaking space trim