Insert Text With String insert_str
Insert substrings at byte indices with String::insert_str and keep indices on char boundaries, since a multi-byte offset makes the call panic.
Code
fn main() {
let mut line = String::from("status=ok attempts=3");
// insert_str 按字节索引插入,索引必须落在字符边界
line.insert_str(0, "[svc] ");
println!("{line}");
let at = line.find(" attempts").unwrap();
line.insert_str(at, " region=eu");
println!("{line}");
// insert 插入单个 char,同样按字节索引
line.insert(0, '*');
println!("{line}");
// 多字节字符内部不是字符边界:先判断再插入
let mut text = String::from("naïve");
let inside = text.find('ï').unwrap() + 1; // 'ï' 占两个字节
println!(
"byte {inside} of {} is a boundary: {}",
text.len(),
text.is_char_boundary(inside)
);
let end = text.len();
if text.is_char_boundary(end) {
text.insert_str(end, "--parsed");
}
println!("{text}");
}How the snippet works
The moving parts are the function main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: fn main()
The run emits 1 labeled section — byte — one per step.
Key statements
let inside = text.find('ï').unwrap() + 1; // 'ï' 占两个字节
println!(
"byte {inside} of {} is a boundary: {}",
text.len(),
text.is_char_boundary(inside)
);
let at = line.find(" attempts").unwrap();
Interactive Tools for This Topic
FAQ
- What does Insert Text With String insert_str print when run?
- Invoke the file as-is — the `byte` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.