The following code prints out:
1
a
2
a
I don't get this. why does this happen?
fn main() {
let s = "a ";
let sv1:Vec<&str> = s.split_whitespace().collect();
println!("{}", sv1.len());
for x in sv1.iter() {
println!("{}", x);
}
let sv2:Vec<&str> = s.split(' ').collect();
println!("{}", sv2.len());
for x in sv2.iter() {
println!("{}", x);
}
}
As per the method docs, split_whitespace returns std::str::SplitWhitespace, which is An iterator over the non-whitespace substrings of a string, separated by any amount of whitespace. which means it can split on multiple whitespaces, and doesn't include empty string in the result.
While for split method,
Contiguous separators are separated by the empty string. as well as Separators at the start or end of a string are neighbored by empty strings.
So in your example, split_whitespace gives ["a"] but split gives ["a", ""].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With