String::insert_str¶
Level: reference · for working programmers
One line: Inserts a &str at a byte offset — insert for text, with the same O(n) shift and the same two panics.
Stable since 1.16.0.
Same rules as insert: byte offset, panics out of range or inside a character, everything after moves.
Inserting at 0 is prepending, which is the job with no cheaper spelling — a String grows at the end, so putting something at the front always costs a copy of the rest. When you are prepending repeatedly, build the pieces in reverse and reverse at the end, or collect from an iterator.
For replacing a range rather than inserting into one, replace_range does both halves at once.
Example¶
string_insert_str.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut s = String::from("world");
s.insert_str(0, "hello, ");
println!("{s:?}");
// Inserting in the middle, at an offset found by searching.
let mut line = String::from("key=value");
if let Some(i) = line.find('=') {
line.insert_str(i, " ");
line.insert_str(i + 2, " ");
}
println!("{line:?}");
// Prepending always copies the rest -- there is no cheap version.
let mut acc = String::new();
for word in ["c", "b", "a"] {
acc.insert_str(0, word);
}
println!("{acc:?}");
// Replacing a range instead of inserting into one.
let mut r = String::from("key=value");
r.replace_range(3..4, " -> ");
println!("{r:?}");
}
Verified output of string_insert_str.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::insert— one character instead of textString::replace_range— replacing rather than insertingString::push_str— appending, which does not shift anythingstr::find— locating the offset
String::insert_str in the standard library ↗
Po polsku¶
Reguły są dokładnie te same co przy insert — przesunięcie w bajtach, panika poza zakresem albo w środku znaku, przepchnięcie całej reszty — ale przykład odsłania pułapkę, która przy jednym char mniej boli: przesunięcia policzone przed wstawieniem tracą po nim ważność. Dlatego po line.insert_str(i, " ") drugie wywołanie sięga po i + 2, a nie i + 1: jeden bajt doszedł ze spacją, a = wciąż zajmuje swój własny. Wstawienie pod indeksem 0 to dopisanie na początek i nie ma na to tańszego zapisu — String rośnie od końca, więc każde „na przód” kopiuje całą resztę; przy wielokrotnym dopisywaniu na początek buduj po kolei i odwróć na koniec albo zbierz wynik z iteratora. A jeśli chcesz zakres podmienić, a nie wcisnąć się w niego, replace_range robi obie połowy naraz: "key=value" → "key -> value".
Szukaj po polsku: wstawianie na początek łańcucha znaków · nieaktualne przesunięcie po wstawieniu · rust String::insert_str · rust replace_range