Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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, ",")
    ["Elixir", " testing 1", "2", "3! Testing!"]
    
  4. 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!"]
    
  5. Split...