St

Strings in Elixir

59 exercises

About Strings

Strings in Elixir are delimited by double quotes, and they are encoded in UTF-8:

"Hi!"

Strings can be concatenated using the <>/2 operator:

"Welcome to" <> " " <> "New York"
# => "Welcome to New York"

Strings in Elixir support interpolation using the #{} syntax:

"6 * 7 = #{6 * 7}"
# => "6 * 7 = 42"

Any Elixir expression is valid inside the interpolation. If a string is given, the string is interpolated as is. If any other value is given, Elixir will attempt to convert it to a string.

"Elixir can convert booleans to strings: #{true}"
# => "Elixir can convert booleans to strings: true"

"And #{["lists", ", ", "too!"]}"
# => "And lists, too!"

"But not functions: #{fn x -> x end}"

# => ** (Protocol.UndefinedError) protocol String.Chars not implemented for #Function<7.126501267/1 in :erl_eval.expr/5> of type Function
#        (elixir 1.10.1) lib/string/chars.ex:3: String.Chars.impl_for!/1
#        (elixir 1.10.1) lib/string/chars.ex:22: String.Chars.to_string/1

Elixir provides many functions for working with strings in the String module. If you are unsure how to process a string in the way you need it, make sure to browse functions available in the String module and you will most likely find what you need.

String.downcase("PLEASE NO SHOUTING")
# => "please no shouting"

String.split("hello", "", trim: true)
# => ["h", "e", "l", "l", "o"]

String.replace("Do I enjoy Elixir? Maybe...", "Maybe...", "Definitely!")
# => "Do I enjoy Elixir? Definitely!"

String.at("12345", 2)
# => "3"

Using some of those functions, remember that the first character in a string has the index 0.

Some characters need to be escaped to be put in a string, e.g. newlines, double-quotes, or the # character:

"\"A\" is the \#1st letter of the alphabet.\n"

To comfortably work with texts with a lot of newlines, use the triple-double-quote heredoc syntax instead:

"""
1
2
3
"""

You will very often find this syntax used for documenting code:

defmodule MyApp.Hello do
  @moduledoc """
  This is the Hello module.
  """

  @doc """
  Says hello to the given `name`.

  Returns `:ok`.

  ## Examples

      iex> MyApp.Hello.world(:john)
      :ok

  """
  def world(name) do
    IO.puts("hello #{name}")
  end
end
Edit via GitHub The link opens in a new window or tab

Learn Strings

Practicing is locked

Unlock 10 more exercises to practice Strings