str::trim¶
Level: reference · for working programmers
One line: Removes leading and trailing Unicode whitespace, returning a borrowed sub-slice — nothing is allocated and the original is unchanged.
Stable since 1.0.0.
The return type is &str, not String. trim cannot modify the string it is called on — str has no way to change its own length — so it hands back a window onto the same bytes with the ends moved in. That is why it is free, and why s.trim(); on its own line is a no-op the compiler warns about.
Whitespace means char::is_whitespace: the Unicode definition, including tabs, newlines, non-breaking space and the exotic ones. trim_ascii is the narrower, const-capable version.
The interior is untouched — " a b ".trim() is "a b".
This is the first call in almost every input-handling path, and the reason is is_empty: a field the user tabbed through arrives as " ", which is not empty until you trim it.
Example¶
str_trim.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let padded = " \t hello world \n ";
println!("{:?}", padded.trim());
println!("{:?} unchanged", padded);
// Only the ends; the interior is left alone.
println!("{:?}", " a b ".trim());
// Borrowed, not allocated: the result is a window on the same bytes.
let owner = String::from(" hi ");
let view: &str = owner.trim();
println!("{:?} from a {}-byte owner", view, owner.len());
// Unicode whitespace counts.
println!("{:?}", "\u{00A0}hi\u{2003}".trim());
// The input-handling reason it exists.
for field in ["", " ", " x "] {
println!("{:<5} empty={:<5} trimmed empty={}",
format!("{field:?}"), field.is_empty(), field.trim().is_empty());
}
}
Verified output of str_trim.rs — regenerated by tools/run_examples.py, never hand-typed.
"hello world"
" \t hello world \n " unchanged
"a b"
"hi" from a 6-byte owner
"hi"
"" empty=true trimmed empty=true
" " empty=false trimmed empty=true
" x " empty=false trimmed empty=false
See also¶
str::trim_start— the front onlystr::trim_end— the back onlystr::trim_matches— trim something other than whitespacestr::trim_ascii— the ASCII-only,constversionstr::is_empty— what to ask after trimming
str::trim in the standard library ↗
Po polsku¶
Wbrew nazwie trim niczego nie obcina: zwraca wycinek łańcucha (&str), czyli okno na te same bajty z przesuniętymi końcami — oryginał zostaje nietknięty, nic się nie alokuje, a samodzielna linijka s.trim(); jest pustą instrukcją, o czym kompilator uprzejmie poinformuje. Nawyk z Pythona (strip) czy z Javy podpowiada tu coś przeciwnego, więc warto zapamiętać typ zwracany, a nie czasownik. Dla polskich danych ważne jest, że „biały znak” oznacza tutaj char::is_whitespace, czyli pełną definicję unikodową — łapie także twardą spację (U+00A0), której w polskim tekście jest mnóstwo, bo typografia każe ją stawiać po jednoliterowych wyrazach w rodzaju „w”, „z”, „i”, „a”; trim_ascii zostawi ją na miejscu. I ta jedna rzecz, dla której trim stoi na początku niemal każdej ścieżki obsługi wejścia: pole, przez które użytkownik tylko przeskoczył tabulatorem, przychodzi jako " ", a is_empty() odpowiada wtedy false — dopiero field.trim().is_empty() daje true.
Szukaj po polsku: usuwanie białych znaków · twarda spacja w łańcuchu · rust trim returns &str · rust trim vs trim_ascii