Skip to content

str::trim_start

str methods · Strings

Level: reference · for working programmers

One line: trim at the front only — leading whitespace removed, trailing whitespace kept.

pub fn trim_start(&self) -> &str

Stable since 1.30.0.

"Start" means the beginning of the string in memory order, not the left-hand side on screen. For right-to-left text the two differ, which is exactly why the method was renamed from trim_left in Rust 1.33: the old name described a visual position that depends on the script, the new one describes a byte position that does not.

Borrowed like trim; nothing is allocated.

Useful when trailing content is significant — preserving indentation-stripped lines that must keep their line ending, or normalizing a value while leaving a deliberate trailing marker in place.

Example

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

fn main() {
    let s = "   indented   ";
    println!("{:?}", s.trim_start());
    println!("{:?}", s.trim_end());
    println!("{:?}", s.trim());

    // Stripping indentation while keeping the line ending.
    let block = "    alpha\n    beta\n";
    let stripped: String = block.lines().map(|l| format!("{}\n", l.trim_start())).collect();
    print!("{stripped}");

    // "start" is memory order, not the left of the screen — which is why
    // trim_left was renamed. Here the leading char is Hebrew, not whitespace.
    let rtl = "  \u{05D0}\u{05D1}  ";
    println!("{:?}", rtl.trim_start());
}

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

"indented   "
"   indented"
"indented"
alpha
beta
"אב  "

See also

str::trim_start in the standard library ↗

Po polsku

trim_start zdejmuje białe znaki tylko z przodu i — co zwykle jest całym powodem, dla którego się po nią sięga — zostawia to, co na końcu: " indented " staje się "indented ", ze spacjami po prawej nietkniętymi. Nic się przy tym nie alokuje, bo wynikiem jest wycinek łańcucha (&str) wskazujący w środek oryginału, więc zdejmowanie wcięcia z każdego wiersza w pętli jest tanie. Słowo „start” oznacza początek w kolejności bajtów, a nie lewą krawędź ekranu: w ostatnim wierszu przykładu znikają dwie spacje stojące w pamięci przed hebrajskimi znakami, choć terminal rysuje ten napis od prawej do lewej. Stara nazwa trim_left opisywała położenie zależne od pisma i właśnie dlatego zastąpiono ją w wersji 1.33.

Szukaj po polsku: usuwanie białych znaków z początku łańcucha · zdejmowanie wcięć z wierszy · rust trim_start · rust trim_left renamed trim_start