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?
Issues with your original code:
snake_case
, types and traits use CamelCase
."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
.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
).char_indices
is a good tool here.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
.