Warm tip: This article is reproduced from serverfault.com, please click

How to "crop" characters off the beginning of a string in Rust?

发布于 2016-07-19 00:22:32

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.

If I write

let mut example = "stringofletters";
CropLetters(example, 3);
println!("{}", example);

then the output should be:

ingofletters

Is there any way I can do this?

Questioner
LonelyPyxel
Viewed
0
Shepmaster 2018-12-31 23:06:22

Issues with your original code:

  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);
}

See Chris Emerson's answer if you don't actually need to modify the original String.