Learn/Elixir/8. Strings and a small project
Lesson 8 of 8
Sign in

Elixir, lesson 8

Strings and a small project

Text is everywhere: names, commands, files, messages. Elixir strings are UTF-8, which means they handle accents and emoji correctly, and the String module gives you the tools to work with them.

Everyday string functions

Like everything in Elixir, these return new strings; s itself never changes.

One subtle point: String.length/1 counts graphemes, the characters a human sees. The function byte_size/1 counts the bytes in memory, which is larger for letters like é. When you care about what a reader sees, use the String functions.

Taking text apart and putting it back

String.split/2 cuts a string at a separator and gives you a list. glues a list back together:

2 exercises to try what you just read.

Exercise 1

Shout, flip and count

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

Enum.join/2

String.graphemes/1 splits a string into its single characters, which is perfect for counting or filtering letters:

To check one character against several options, use in with a list: ch in ["a", "e", "i", "o", "u"].

Lining text up

String.pad_leading/2 and String.pad_trailing/2 add spaces until a string reaches a given width, which is how you build neat columns:

Putting it all together

The final exercise is a small program that uses every lesson so far: reading input, converting numbers, a module with functions, a list of tuples, Enum to total things up, a decision for an empty receipt, and interpolation for the output. A good plan:

  1. Read N, then N lines.
  2. Turn each line into a tuple {name, qty, price} with a helper function.
  3. Print one line per item.
  4. Sum the quantities and the line totals with Enum.
  5. Find the most expensive line with Enum.max_by/2, which keeps the first item when two are equal.

Further reading

  • The String module
  • Getting started: Binaries, strings, and charlists
  • Enum.max_by/4

Read one line of text and print three lines:

  1. the text in uppercase,
  2. the text reversed,
  3. Vowels: N, where N counts the letters a e i o u in either case.

Input: one line (letters, spaces and punctuation; it may be empty).

prints

Print a receipt for a shopping trip.

Input: the first line is the number of items N (0 or more). Each of the next N lines has an item name (one word), a quantity and a unit price in whole euros, separated by spaces.

Output:

  • one line per item, in input order: name xQTY = LINE_TOTAL,
  • then Items: and the sum of all quantities,
  • then Total: and the sum of all line totals,
  • then Biggest: and the name of the item with the largest line total (the first one if there is a tie), or none if there are no items.

prints

s = "Hello, Elixir"

String.upcase(s)              # "HELLO, ELIXIR"
String.downcase(s)            # "hello, elixir"
String.length(s)              # 13
String.reverse(s)             # "rixilE ,olleH"
String.contains?(s, "Elixir") # true
String.starts_with?(s, "He")  # true
String.replace(s, "l", "L")   # "HeLLo, ELixir"
String.slice(s, 0, 5)         # "Hello"
"red,green,blue" |> String.split(",")      # ["red", "green", "blue"]
["a", "b", "c"] |> Enum.join("-")          # "a-b-c"
"banana"
|> String.graphemes()
|> Enum.count(fn ch -> ch == "a" end)      # 3
String.pad_leading("42", 5)    # "   42"
String.pad_trailing("tea", 6)  # "tea   "
Hello there
HELLO THERE
ereht olleH
Vowels: 4
3
apple 3 2
bread 1 4
cheese 2 5
apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese