我想要一个函数,它可以接受两个参数 (string, number of letters to crop off front)
并返回相同的字符串,除了字符 x 之前的字母不见了.
如果我写
let mut example = "stringofletters";
CropLetters(example, 3);
println!("{}", example);
那么输出应该是:
ingofletters
有什么办法可以做到这一点吗?
最佳答案
在许多用途中,简单地返回输入的一部分是有意义的,避免任何复制。转换 @Shepmaster's solution使用不可变切片:
fn crop_letters(s: &str, pos: usize) -> &str {
match s.char_indices().skip(pos).next() {
Some((pos, _)) => &s[pos..],
None => "",
}
}
fn main() {
let example = "stringofletters"; // works with a String if you take a reference
let cropped = crop_letters(example, 3);
println!("{}", cropped);
}
相对于变异版本的优势是:
- 不需要副本。如果你想要一个新分配的结果,你可以调用
cropped.to_string()
;但你不必这样做。 - 它适用于静态字符串切片以及可变
String
等。
缺点是,如果您确实有一个要修改的可变字符串,那么效率会稍微低一些,因为您需要分配一个新的 String
。
关于string - 如何从 Rust 中的字符串开头删除 "crop"个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447780/