How to split a string on a given char value (e.g. space)

I am looking for a method to split a string into a vector of sub-strings separated by a given char value, e.g.
"0123 4567" => vec!["0123" "4567"]

Good news then, there is split. I suspect you're newish, so the signatures might be somewhat hard to read, but the examples do convey the most important uses. If you need something different or want some more explanation, let us know :slight_smile:

All the versions I have seen of split (1) use a predicate instead of a value and (2) produce an iterator instead of a vector. Is my requirement too simple?

Not sure what you meadn by "too simple", but the split function does indeed pack quite a bit of generics.

First, it splits on a pattern, but both &str as well as char qualify, so you can use it in your case (see the first example).

Returning an Iterator is a pretty rusty thing to do, and helps writing idiomatic, well-performing code. But you can stick the results in a Vec if you want, but you'd need to use collect as shown in the examples.

Overall, this method works for what you described, so go ahead and use it is what I'd suggest :slight_smile:

1 Like

I have now seen the examples in the std doc, and what I want is accomplished by .split(' ').collect(). Thanks for the reference.

3 Likes