From the documentation, it's not clear. In Java you could use the split
method like so:
"some string 123 ffd".split("123");
From the documentation, it's not clear. In Java you could use the split
method like so:
"some string 123 ffd".split("123");
There is a special method
split
for structString
:Split by char:
Split by string:
Split by closure:
split
returns anIterator
, which you can convert into aVec
usingcollect
:split_line.collect::<Vec<_>>()
. Going through an iterator instead of returning aVec
directly has several advantages:split
is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values:split_line.take(2).collect::<Vec<_>>()
, or even if you need only the first value that can be converted to an integer:split_line.filter_map(|x| x.parse::<i32>().ok()).next()
. This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".split
makes no assumption on the way you want to store the result. You can use aVec
, but you can also use anything that implementsFromIterator<&str>
, for example aLinkedList
or aVecDeque
, or any custom type that implementsFromIterator<&str>
.Use
split()
This gives an iterator, which you can loop over, or
collect()
into a vector.There are three simple ways:
By separator:
By whitespace:
By newlines:
The result of each kind is an iterator:
There's also
split_whitespace()