O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  1. Define a string to work with:
    iex(1)> my_string = "Elixir, testing 1,2,3! Testing!"
    "Elixir, testing 1,2,3! Testing!"
    
  2. Split a string at the whitespaces:
    iex(2)> String.split(my_string)
    ["Elixir,", "testing", "1,2,3!", "Testing!"]
    
  3. Split a string at a given character, in this case at ,:
    iex(3)> String.split(my_string, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required