`String.split` remove all the whitespace unexpectly

I have String containing serveral \ns, like this:

let b = String::from("\nret:    0.11\nsr:     2.47\nprofit: 11.01\ncomm:   0.95\nslip:   3.34\nto_day: 1.08\nto_sum: 2202\nhold:   83.31");

I split it with \n:

b.to_string().split("\n").collect_vec()

And the split result is this:

""
"ret: 0.11"
"sr: 2.47"
"profit: 11.01"
"comm: 0.95"
"slip: 3.34"
"to_day: 1.08"
"to_sum: 2202"
"hold: 83.31"

As can be seen, the whitespace from the res is gone, what should I do to keep the whitespace in the split res?

Can you please share a complete example? The following example works as expected on the Playground:

fn main() {
    let b = String::from("\nret:    0.11\nsr:     2.47\nprofit: 11.01\ncomm:   0.95\nslip:   3.34\nto_day: 1.08\nto_sum: 2202\nhold:   83.31");
    let v: Vec<_> = b.split("\n").collect();
    dbg!(v);
}
2 Likes

My bad, you are right. It didn't remove the whitespace, it just because of the showing style from the notebook.
Thank you for your reply.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.