1

I have a Vec<&str>, containing empty strings. I'd like to write a function join_and_partition_on_empty, that returns a Vec<&str> where all the non-empty strings are joined with a space and the empty strings are removed, creating new string starts.

// example test
assert_eq!(
   join_and_partition_on_empty(vec!["a", "", "b", "c", "", "d", "e" ],
   vec!["a", "b c", "d e" ]
)

I have tried using an iterator and fold, but ran into ownership problems when trying to concatenate strings.

1
  • 3
    You can't return a Vec<&str> since you have to create new data, so you should return a Vec<String> instead. Commented Dec 5, 2020 at 23:18

1 Answer 1

3

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(" "));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.