Why does this String.split() not work

I set sentence to a string. When I pipe it into String.split(’’) it doesn’t work. Variations of String.split() do not work either. What fundamental piece of knowledge am I missing here?

sentence = "one fish two fish red fish blue fish"
sentence |> String.split('')
** (ArgumentError) argument error
    (stdlib) :binary.split("one fish two fish red fish blue fish", [], [:global])
    (elixir) lib/string.ex:424: String.split/3

When I try a RegEx, it does work. For example:

sentence |> String.split(~r/[\s_]/)

returns what I expected from the first code example.

Why is that?

1 Like

Elixir strings use double quotes. Single quotes are used to construct Charlists https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#charlists

Try sentence |> String.split("")


To add to @bnhansn response, you’ve hit a somewhat unfortunate edge case. '' is the same as [], String.split does accept a list of strings to split on, so you can do for example this:

iex> String.split("1,2 3,4", [" ", ","])
["1", "2", "3", "4"]

but yeah, it doesn’t work on an empty list.