Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

rust

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?

like image 513
LonelyPyxel Avatar asked Dec 08 '22 21:12

LonelyPyxel


1 Answers

In many uses it would make sense to simply return a slice of the input, avoiding any copy. Converting @Shepmaster's solution to use immutable slices:

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

Advantages over the mutating version are:

  • No copy is needed. You can call cropped.to_string() if you want a newly allocated result; but you don't have to.
  • It works with static string slices as well as mutable String etc.

The disadvantage is that if you really do have a mutable string you want to modify, it would be slightly less efficient as you'd need to allocate a new String.

like image 147
Chris Emerson Avatar answered Mar 23 '23 00:03

Chris Emerson