Home > OS >  Unexpected string split behaviour
Unexpected string split behaviour

Time:06-20

I am reading rustbook and came across the following piece of code:

fn main() {
    "Hello, world!".split("#").next().expect("some message");
}

I ran it, but the program didn't panic, although there is no such symbol in the string and the iterator should have returned None when calling next().

After that I went to the documentation and for some reason I didn't find an example with splitting by a pattern which doesn't exist in the string.

Please explain why None is not returned in this case.

CodePudding user response:

"Hello, world!".split("#") successfully splits the string at every occurrence of #. If there are N hash signs in the string, then the resulting iterator will iterate over N 1 delimited substrings. In your case, there are 0 hash signs, so you get one substring: namely, the whole string itself.

  • Related