Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a vector into a vector of slices based on a separator?

Tags:

rust

If I have a vector such as

let mut bytes = vec![0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];

I want to separate the vector by the 0x40 separator. Is there a clean way of doing this functionality?

expected output: [[0x01, 0x02, 0x03], [0x04, 0x05], [0x06]]

like image 555
user12913833 Avatar asked Feb 17 '20 16:02

user12913833


People also ask

How do I split a vector in R?

Use the split() function in R to split a vector or data frame. Use the unsplit() method to retrieve the split vector or data frame.

How do I separate a list in R?

To split the data frame in R, use the split() function. You can split a data set into subsets based on one or more variables representing groups of the data.


1 Answers

Use slice::split:

fn main() {
    let bytes = [0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];
    let pieces: Vec<_> = bytes
        .split(|&e| e == 0x40)
        .filter(|v| !v.is_empty())
        .collect();
    println!("{:?}", pieces)
}

See also:

  • How can slices be split using another slice as a delimiter?
  • In Rust, what's the idiomatic way to split a &str into an iterator of &strs of one character each?
like image 111
Shepmaster Avatar answered Nov 15 '22 07:11

Shepmaster