How do I split a string in Rust?

前端 未结 5 1109
情深已故
情深已故 2020-11-30 19:18

From the documentation, it\'s not clear. In Java you could use the split method like so:

\"some string          


        
5条回答
  •  温柔的废话
    2020-11-30 20:21

    split returns an Iterator, which you can convert into a Vec using collect: split_line.collect::>(). Going through an iterator instead of returning a Vec 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::>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::().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 a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.

提交回复
热议问题