Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between split(' ') and split_whitespace()

Tags:

rust

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);
    }
}
like image 866
Hee Hwang Avatar asked Sep 02 '26 14:09

Hee Hwang


1 Answers

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", ""].

like image 150
Psidom Avatar answered Sep 04 '26 12:09

Psidom