如何“裁剪"Rust 中字符串开头的字符? [英] How to "crop" characters off the beginning of a string in Rust?
本文介绍了如何“裁剪"Rust 中字符串开头的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个函数,它可以接受两个参数 (字符串,要从前面裁剪的字母数)
并返回相同的字符串,除了字符 x 之前的字母不见了.
I want a function that can take two arguments (string, number of letters to crop off front)
and return the same string except with the letters before character x gone.
如果我写
let mut example = "stringofletters";
CropLetters(example, 3);
println!("{}", example);
那么输出应该是:
ingofletters
有什么办法可以做到这一点吗?
Is there any way I can do this?
推荐答案
原始代码的问题:
- 函数使用
snake_case
,类型和特征使用CamelCase
. "foo"
是&str
类型的字符串文字.这些可能不会改变.您将需要一些已分配给堆的内容,例如String
.- 调用
crop_letters(stringofletters, 3)
会将stringofletters
的所有权转移给该方法,这意味着您将无法不再使用该变量.您必须传入一个可变引用 (&mut
). - Rust 字符串不是 ASCII,它们是 UTF-8.您需要弄清楚每个字符需要多少字节.
char_indices
是一个很好的工具. - 您需要处理字符串少于 3 个字符的情况.
- 一旦获得字符串新开头的字节位置,就可以使用
drain
将一大块字节移出字符串.我们只是删除这些字节,让String
移动到剩余的字节上.
- Functions use
snake_case
, types and traits useCamelCase
. "foo"
is a string literal of type&str
. These may not be changed. You will need something that has been heap-allocated, such as aString
.- The call
crop_letters(stringofletters, 3)
would transfer ownership ofstringofletters
to the method, which means you wouldn't be able to use the variable anymore. You must pass in a mutable reference (&mut
). - Rust strings are not ASCII, they are UTF-8. You need to figure out how many bytes each character requires.
char_indices
is a good tool here. - You need to handle the case of when the string is shorter than 3 characters.
- Once you have the byte position of the new beginning of the string, you can use
drain
to move a chunk of bytes out of the string. We just drop these bytes and let theString
move over the remaining bytes.
fn crop_letters(s: &mut String, pos: usize) {
match s.char_indices().nth(pos) {
Some((pos, _)) => {
s.drain(..pos);
}
None => {
s.clear();
}
}
}
fn main() {
let mut example = String::from("stringofletters");
crop_letters(&mut example, 3);
assert_eq!("ingofletters", example);
}
如果您实际上不需要修改原始 String
,请参阅 Chris Emerson 的回答.
See Chris Emerson's answer if you don't actually need to modify the original String
.
这篇关于如何“裁剪"Rust 中字符串开头的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文