String Functions in Elixir

The standard library in Elixir provides many useful string-related functions. Here are some examples to give you a sense of the available operations.

defmodule StringFunctions do
  def main do
    # We define a shorthand for IO.puts to make the example more concise
    p = &IO.puts("#{elem(&1, 0)}  #{elem(&1, 1)}")

    # Here's a sample of the functions available for strings in Elixir.
    # Note that in Elixir, strings are typically manipulated using the
    # String module, and some operations are available as direct functions
    # on strings (which are actually binaries in Elixir).

    p.{"Contains:", String.contains?("test", "es")}
    p.{"Count:", length(String.split("test", "t", trim: true)) - 1}
    p.{"Starts with:", String.starts_with?("test", "te")}
    p.{"Ends with:", String.ends_with?("test", "st")}
    p.{"Index:", :binary.match("test", "e") |> elem(0)}
    p.{"Join:", Enum.join(["a", "b"], "-")}
    p.{"Repeat:", String.duplicate("a", 5)}
    p.{"Replace (all):", String.replace("foo", "o", "0")}
    p.{"Replace (once):", String.replace("foo", "o", "0", global: false)}
    p.{"Split:", inspect(String.split("a-b-c-d-e", "-"))}
    p.{"Lowercase:", String.downcase("TEST")}
    p.{"Uppercase:", String.upcase("test")}
  end
end

StringFunctions.main()

This script demonstrates various string operations in Elixir. Here’s a brief explanation of what each function does:

  • String.contains?/2: Checks if a string contains a substring.
  • String.split/3 with length/1: Used to count occurrences (Elixir doesn’t have a direct count function).
  • String.starts_with?/2 and String.ends_with?/2: Check string prefixes and suffixes.
  • :binary.match/2: Finds the index of a substring (Elixir strings are binaries).
  • Enum.join/2: Joins a list of strings with a separator.
  • String.duplicate/2: Repeats a string a specified number of times.
  • String.replace/4: Replaces occurrences in a string, with an option for global or single replacement.
  • String.split/3: Splits a string by a delimiter.
  • String.downcase/1 and String.upcase/1: Convert string case.

To run this script, save it as string_functions.exs and execute it with:

$ elixir string_functions.exs
Contains:  true
Count:  2
Starts with:  true
Ends with:  true
Index:  1
Join:  a-b
Repeat:  aaaaa
Replace (all):  f00
Replace (once):  f0o
Split:  ["a", "b", "c", "d", "e"]
Lowercase:  test
Uppercase:  TEST

This example showcases Elixir’s string manipulation capabilities, which are primarily provided by the String module. Elixir’s approach to strings is a bit different from some other languages, as strings in Elixir are actually UTF-8 encoded binaries. This allows for efficient processing of Unicode strings.