Given a vector <Vec<usize>>
of indices indicating where to split a string as follows:
println!("{:?}", idxs);
[2, 1, 6, 2, 5, 2, 2, 1]
And the following string (The Series column in the Bureau of Labor Statistics' data):
let mut sstr = "JTS000000000000000JOR";
I wrote a recursive function to split the string as follows:
fn split_str(cur: &str, rest: &str, idxs: Vec<usize>, mut res: Vec<String>) -> Vec<String> {
if idxs.len() > 1 {
//println!("cur: {} idx: {} rest: {}", cur, *idxs.first().unwrap(), rest);
res.push(cur.to_owned());
let (cur, rest) = rest.split_at(*idxs.first().unwrap());
split_str(cur, rest, idxs[1..].to_vec(), res)
}
else {
res.push(cur.to_string());
//println!("{}", rest);
res[1..].to_vec()
}
}
The method is run as follows:
let r = split_str(&sstr[0..idxs[0]], &sstr[(idxs[1]+1)..], idxs[1..].to_vec(), vec!["".to_string()]);
which correctly returns
["JT", "S", "000000", "00", "00000", "00", "JO", "R"]
How can I optimize this code? I'm used to Scala and it feels like I'm forcing Rust into a pattern it wasn't designed for, but I don't want to revert to traditional loops.