Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string multiple times in Rust?

Tags:

iterator

rust

With a string like "1 foo\n2 bar\n3 foobar", how do I split it into:

[["1", "foo"], ["2", "bar"] ["3", "foobar"]]
like image 682
lightsing Avatar asked Apr 17 '26 20:04

lightsing


1 Answers

This will work.

fn main() {
    let string: Vec<Vec<&str>> = "1 foo\n2 bar\n3 foobar".split('\n')
        .map(|x: &str| x.split(' ').collect())
        .collect();
    println!("{:?}", string);
}
like image 172
lightsing Avatar answered Apr 19 '26 12:04

lightsing