如何“裁剪"Rust 中字符串开头的字符? [英] How to "crop" characters off the beginning of a string in Rust?

查看:71
本文介绍了如何“裁剪"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?

推荐答案

原始代码的问题:

  1. 函数使用snake_case,类型和特征使用CamelCase.
  2. "foo"&str 类型的字符串文字.这些可能不会改变.您将需要一些已分配给堆的内容,例如 String.
  3. 调用 crop_letters(stringofletters, 3) 会将 stringofletters 的所有权转移给该方法,这意味着您将无法不再使用该变量.您必须传入一个可变引用 (&mut).
  4. Rust 字符串不是 ASCII,它们是 UTF-8.您需要弄清楚每个字符需要多少字节.char_indices 是一个很好的工具.
  5. 您需要处理字符串少于 3 个字符的情况.
  6. 一旦获得字符串新开头的字节位置,就可以使用 drain 将一大块字节移出字符串.我们只是删除这些字节,让 String 移动到剩余的字节上.
  1. Functions use snake_case, types and traits use CamelCase.
  2. "foo" is a string literal of type &str. These may not be changed. You will need something that has been heap-allocated, such as a String.
  3. The call crop_letters(stringofletters, 3) would transfer ownership of stringofletters to the method, which means you wouldn't be able to use the variable anymore. You must pass in a mutable reference (&mut).
  4. 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.
  5. You need to handle the case of when the string is shorter than 3 characters.
  6. 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 the String 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆