Why can I not reverse the result of str::split?

前端 未结 3 964
太阳男子
太阳男子 2021-01-19 06:04

According to the docs for Split, there is a rev method on the result of doing split on a string:

fn main() {
    let mut length = 0;         


        
3条回答
  •  长发绾君心
    2021-01-19 06:25

    The other answers are correct, but I want to point out rsplit. This is probably more obvious and more performant.

    So, why can't you use rev? As other answers state, it's not implemented for StrSearcher. But why is it not implemented? From the DoubleEndedSearcher docs:

    For this, the impl of Searcher and ReverseSearcher need to follow these conditions:

    • All results of next() need to be identical to the results of next_back() in reverse order.
    • next() and next_back() need to behave as the two ends of a range of values, that is they can not "walk past each other".

    The problem with reversing the iterator using strings is this:

    "baaab".split("aa") // -> ["b", "aa", "ab"];
    

    However, if you were to start at the end of the string, you'd get something like:

    "baaab".split("aa").rev() // -> ["b", "aa", "ba"]
    

    Which is clearly not the same set of items in a different order!

    Simply put, you can't reverse an iterator that is split on strings because there's no efficient way of knowing when the next result is. You'd have to split the entire string into a collection, then reverse the collection!

    This is why rsplit exists - it means start at the end of the string and split to the beginning, in an efficient manner.

提交回复
热议问题