实现说明
String insert_str 按字节索引插入可以归结为函数 main。
使用要点
- 每一步打印都带着自己的标签:
byte。
常见问题
运行「String insert_str 按字节索引插入」会打印什么?
运行文件本身,byte 这些前缀各对应一段演示逻辑。
核心语句
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();
代码示例
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}");
}