Correct way to split a string


#1

In python I can do test = “A string”.split(" ")[1] And then the value of test will be “string”. How can I correctly do this in rust? I have fair knowledge with rust but I never quite understood how splitting strings work.


#2

this forum is about language discussion, please post this kind of questions to stackoverflow.

in rust the split function returns a lazy iterator. you cannot index lazy iterators (why i don’t know, would be trivial to implement). so you need to use the function nth. an example on playpen is here: http://is.gd/Im41JI


#3

Oh alright. Thank you.


#4

It would only be trivial (and correct) to implement on iterators that implement RandomAccessIterator.


#5

why? as long as you only implement Index and forward the call to nth, you get the expected behaviour.


#6

Then you’ll have users asking you why this doesn’t work:

 let mut spl = "x y z".split(' ');
 let a = spl[1];
 let b = spl[2];

Or maybe it does work, if the split iterator is Copy? But then we can fool users into O(N^2) algorithms.


#7

hmm right… lets not do that. we can always collect and index :slight_smile: