The splitn()
method returns an iterator over the parts, so the only way to access them is to actually iterate over them. If you know that there always will be two parts, you can do this:
let mut iter = message.splitn(2, ' ');
let command = iter.next().unwrap();
let options = iter.next().unwrap();
This will work fine as long as message
contains at least one space character. For a message without a space, this will panic on the last line, since the iterator is already terminated, so you would call unwrap()
on None
. (Note that you need 2 as the first argument to splitn()
if you want to get two items.)
Starting from Rust 1.52, you can use the split_once()
method:
if let Some((command, options)) = message.split_once(' ') {
// handle command, options
} else {
// handle error
}
As pointed out in the comments, another option is to use str::split_at()
together with str::find()
:
let (command, options) = message.split_at(message.find(' ').unwrap());
Note that the space character will be included in options
with this solution, whereas the other approaches don't include it.
str::split_at
withIterator::position
might also be handy – Magritte