How can I return a vector of strings by splitting a string that has spaces in between

How can I return a vector of strings by splitting a string that has spaces in between

fn line_to_words(line: &str) -> Vec<String> {
  line.split_whitespace().collect()
}

fn main() {

    println!( "{:?}", line_to_words( "string with spaces in between" ) );

}

You need to transform the iterator's item type from &str to String; for example, by doing

line.split_whitespace().map(str::to_string).collect()

You can also map From::from or Into::into to achieve the same result.

2 Likes

In this case it's possible to return views into the original input string, so you can return Vec<&str>.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.