Skip to content

str::split and str::splitn doc unclear as to how empty string input is handled #14222

Closed
@pnkfelix

Description

@pnkfelix

Here's the doc for str::split and str::splitn:

http://static.rust-lang.org/doc/master/core/str/trait.StrSlice.html#tymethod.split

Pop quiz: what does this program print. In particular, what will the first call to next() return when we are doing a split over the empty string? (Also, should it do something else? But that's not as important to me as making the doc clear.)

fn take_three<'a, I:Iterator<&'a str>>(input: &str, variant: &str, mut i: I) {
    let fst = i.next();
    let snd = if fst.is_some() { i.next() } else { None };
    let thd = if snd.is_some() { i.next() } else { None };
    println!("{:8} {:3}: {} {} {}",
             format!("`{}`", input), variant, fst, snd, thd);
}

fn main() {
    let i = "a.b";
    take_three(i,   "", i.split('.'));

    let i = ".";
    take_three(i,   "", i.split('.'));

    let i = "";
    take_three(i,   "", i.split('.'));

    let i = "a.b";
    take_three(i, "n1", i.splitn('.', 1));

    let i = ".";
    take_three(i, "n1", i.splitn('.', 1));

    let i = "";
    take_three(i, "n1", i.splitn('.', 1));

    let i = "a.b";
    take_three(i, "n0", i.splitn('.', 0));

    let i = ".";
    take_three(i, "n0", i.splitn('.', 0));

    let i = "";
    take_three(i, "n0", i.splitn('.', 0));
}

(To be fair: this is not one of those trick questions where splitn's behavior deviates from split on the empty string. If you have the correct intuition about how one behaves, then you'll have the right intuition for the other. But I didn't have an intuition in either direction, which led me to first consult the doc.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions