Does the following meet the requirements?
let input = vec!["a", "", "b", "c", "", "d", "e"];
let res = input
.split(|s| s.is_empty())
.filter(|s| !s.is_empty())
.map(|s| s.join(" "))
.collect::<Vec<_>>();
["a", "b c", "d e"]
If required, one can use filter() to remove extra sub-slices that result due to contiguous empty strings. The input below will produce the same output as listed above:
let input = vec!["a", "", "", "", "", "b", "c", "", "d", "e"];
The above might not be as efficient, as the docs for .split() mention that sub-slices are created for each element that matches the predicate, i.e. empty strings.
As an alternative, here's an imperative method that might be more performant due to ignoring empty strings:
let input = vec!["a", "", "b", "c", "", "d", "e" ];
let mut res = vec![];
let mut group = vec![];
for s in input.iter() {
if !s.is_empty() {
group.push(&s[..]);
} else if !group.is_empty() {
res.push(group.join(" "));
group.clear();
}
}
// Push any remaining values
if !group.is_empty() {
res.push(group.join(" "));
}
Vec<&str>since you have to create new data, so you should return aVec<String>instead.