Skip to content

str::split_terminator

str methods · Strings

Level: reference · for working programmers

One line: split with one change: a trailing empty piece is dropped, so text that ends in its own separator counts correctly.

pub fn split_terminator<P: Pattern>(&self, pat: P) -> SplitTerminator<'_, P>

Stable since 1.0.0.

"a,b,".split(',') is ["a", "b", ""]; split_terminator(',') is ["a", "b"]. The name is the explanation — it treats the pattern as ending each piece rather than separating pieces, which is how a file ending in a newline is meant to be read.

Only the trailing empty goes. Leading and interior empties stay, because they carry information:

input split_terminator(',')
"a,b," ["a", "b"]
",a,b" ["", "a", "b"]
"a,,b" ["a", "", "b"]
"," [""]
"" [] — no pieces at all

That last row is worth noting: the empty string yields nothing, where split yields one empty piece.

For newline-terminated text specifically, lines is this plus \r\n handling.

Example

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

fn main() {
    for input in ["a,b,", ",a,b", "a,,b", ",", ""] {
        println!("{:<7}  split {:<20}  terminator {:?}",
                 format!("{input:?}"),
                 format!("{:?}", input.split(',').collect::<Vec<&str>>()),
                 input.split_terminator(',').collect::<Vec<&str>>());
    }

    // The everyday case: a file that ends in a newline.
    let file = "alpha\nbeta\ngamma\n";
    println!("split {}  terminator {}  lines {}",
             file.split('\n').count(),
             file.split_terminator('\n').count(),
             file.lines().count());
}

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

"a,b,"   split ["a", "b", ""]        terminator ["a", "b"]
",a,b"   split ["", "a", "b"]        terminator ["", "a", "b"]
"a,,b"   split ["a", "", "b"]        terminator ["a", "", "b"]
","      split ["", ""]              terminator [""]
""       split [""]                  terminator []
split 4  terminator 3  lines 3

See also

str::split_terminator in the standard library ↗

Po polsku

Nazwa jest tu całą definicją: split_terminator traktuje wzorzec jako znak kończący element, a nie rozdzielający elementy, dlatego "a,b," daje ["a", "b"] zamiast ["a", "b", ""]. Zysk jest bardzo praktyczny — plik zakończony znakiem nowego wiersza, czyli zwykły plik w konwencji POSIX, przestaje mieć o jeden „wiersz” za dużo; w przykładzie widać to jako split 4 kontra terminator 3 przy trzech liniach tekstu. Znika wyłącznie pusty kawałek z samego końca, bo puste na początku i w środku niosą informację: ",a,b" to dalej ["", "a", "b"], a "a,,b" to ["a", "", "b"] — w danych kolumnowych taka dziura w środku to po prostu pusta komórka. Dwa skrajne przypadki zapamiętaj osobno: "," daje [""], a pusty tekst nie daje nic ([]), choć split zwróciłby w tym miejscu [""]; do tekstu dzielonego na wiersze i tak zwykle lepsze jest lines, które dokłada obsługę \r\n.

Szukaj po polsku: znak kończący a znak rozdzielający · plik zakończony nową linią liczenie wierszy · rust split_terminator vs split · rust trailing empty string split