Why does String.split/2 return empty strings at beginning and end?

This is pretty weird, trying to understand why Elixir does this:

"01" |> String.split("")
["", "0", "1", ""]

"01" |> String.split("", trim: true)
["0", "1"]

Why does the first example return empty strings in the returning list? There’s probably a good reason, trying to learn :smiley:

The documentation for String.split/2 explicitly mentions empty strings, saying:

Splitting on empty string returns graphemes

You can think of it as "there’s an empty string between every pair of graphemes in a string. There’s also an empty string between the start of the string and the first grapheme, sort of. It also helps with having some properties that hold true for String.split/2. You can learn more about that by looking at this test in StreamData, for example.

2 Likes