Splitting strings
Functions to work on strings are defined under the String
module. In the next few recipes, we will be using some of these functions.
In this recipe, we will be focusing on how to split strings using String.split/1
, String.split/3
and String.split_at/2
.
Getting ready
Start a new IEx session by typing iex
in your command line.
How to do it…
To demonstrate the use of the split
functions in the String
module, we will follow these steps:
Define a string to work with:
iex(1)> my_string = "Elixir, testing 1,2,3! Testing!" "Elixir, testing 1,2,3! Testing!"
Split a string at the whitespaces:
iex(2)> String.split(my_string) ["Elixir,", "testing", "1,2,3!", "Testing!"]
Split a string at a given character, in this case at
,
:iex(3)> String.split(my_string, ",") ["Elixir", " testing 1", "2", "3! Testing!"]
Split a string at a given character and limit the number of splits to be performed:
iex(4)> String.split(my_string, ",", parts: 2) ["Elixir", " testing 1,2,3! Testing!"]
Split...