Rust String split

rust methods for string split

Rust - String Split

Spliting a string using Rust is a simple task, thankfully to the STD and the str type that provides some methods to handle the strings. Also takes some time and explore the Rust Playground

By Character

The simplest one, using split method:

fn main() {
  let text = "apple, banana, blueberry";
  let fruits: Vec<&str> = text.split(',').collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry"] Run the code here

By String

Following the same one, but now using a string:

fn main() {
  let text = "apple::banana::blueberry";
  let fruits: Vec<&str> = text.split("::").collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry"] Run the code here

At whitespace

Is a convenient one, using split_whitespace:

fn main() {
  let text = "apple banana blueberry";
  let fruits: Vec<&str> = text.split_whitespace().collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry"] Run the code here

With a Closure

Use the split, pass a clouse with the logic to split:

fn main() {
  let text = "apple1banana2blueberry3";
  let fruits: Vec<&str> = text.split(|c: char| c.is_numeric()).collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry", ""]

Run the code here

Empty Substrings

The last example give us an empty string.

fn main() {
  let text = "apple1banana2blueberry3";
  let fruits: Vec<&str> = text.split(|c: char| c.is_numeric()).collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry", ""]

Now avoiding the empty string:

fn main() {
  let text = "apple1banana2blueberry3";
  let fruits: Vec<&str> = text.split(|c: char| c.is_numeric()).filter(|&s| !s.is_empty()).collect();
  println!("{:?}", fruits);
}

The output should be: ["apple", "banana", "blueberry", ""]

Run the code here

0%