Skip to content

str::split_at_checked

str methods · Strings

Level: reference · for working programmers

One line: split_at returning OptionNone for an offset that is out of range or inside a character.

pub const fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>

Stable since 1.80.0. Usable in a const context.

Same cut, no panic. The two failure modes collapse into one None, so this is the form to use on any offset that came from outside your program: a config value, a terminal width, a byte count from a protocol.

None does not tell you which failure happened. When that matters, ask is_char_boundary and compare against len yourself.

When you want a cut near a requested offset rather than a refusal, floor_char_boundary moves the index back to the nearest legal one — the usual answer for truncating a display string.

Example

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

fn main() {
    let s = "héllo";

    for mid in [0, 1, 2, 3, 5, 6, 99] {
        println!("{mid:>2} -> {:?}", s.split_at_checked(mid));
    }

    // Distinguishing the two refusals, when it matters.
    for mid in [2, 99] {
        let why = if mid > s.len() { "out of range" } else { "inside a character" };
        println!("{mid} refused: {why}");
    }

    // Truncating to a budget: floor the offset rather than refusing.
    let budget = 3;
    let cut = s.floor_char_boundary(budget);
    println!("{:?}", s.split_at(cut));
}

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

 0 -> Some(("", "héllo"))
 1 -> Some(("h", "éllo"))
 2 -> None
 3 -> Some(("hé", "llo"))
 5 -> Some(("héll", "o"))
 6 -> Some(("héllo", ""))
99 -> None
2 refused: inside a character
99 refused: out of range
("hé", "llo")

See also

str::split_at_checked in the standard library ↗

Po polsku

To samo cięcie co split_at, tylko zamiast paniki dostajesz Option — i właśnie ta wersja powinna być domyślna wszędzie tam, gdzie offset przyszedł spoza programu: z pliku konfiguracyjnego, z szerokości terminala, z licznika bajtów w protokole. Za tę wygodę płaci się utratą informacji: oba powody odmowy zlewają się w jedno None, więc po samym wyniku nie odróżnisz „offset poza tekstem” (tu 99) od „offset w środku znaku” (tu 2) — jeśli to rozróżnienie ma znaczenie, trzeba je odtworzyć ręcznie przez is_char_boundary i porównanie z len(). Gdy zaś w ogóle nie chcesz odmowy, tylko cięcia blisko żądanego miejsca — typowo przy skracaniu tekstu do wyświetlenia — właściwą odpowiedzią jest floor_char_boundary, które cofa indeks do najbliższej legalnej granicy. Warto wiedzieć, że split_at_checked jest stabilne dopiero od 1.80.0, więc starsze materiały, w tym polskie, pokazują w tym miejscu ręczne sprawdzanie granicy albo get(..mid).

Szukaj po polsku: bezpieczne cięcie tekstu bez paniki · granica znaku UTF-8 · rust split_at_checked · rust floor_char_boundary truncate