home ~ projects ~ socials

Split A String Into Parts In Rust

Cut 'em Up

This is how I'm splitting a rust string into a vec of strings on with a seperator:

fn main() {
  let input = "this is|the input".to_string();
  let parts: Vec<String> = input
    .split("|")
    .map(|part| part.to_string())
    .collect();
  println!("First part: {}", parts[0]);
  println!("Second part: {}", parts[1]);
}
Output:
First part: this is
Second part: the input

Just &str

You can drop the .map() if you can get away with &str instead of String.

fn main() {
  let input = "this is|the input".to_string();
  let parts: Vec<&str> = input
    .split("|")
    .collect();
  println!("First part: {}", parts[0]);
  println!("Second part: {}", parts[1]);
}
Output:
First part: this is
Second part: the input

The Collect Is Key

I have a tendency to forget about needing the .collect() call. Hopefully, now that I've written this note it'll stick with me. Worst case, I can just look it up here.

-a

-- end of line --