Elixir, lesson 8
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.
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.
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.
Enum.join/2String.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"].
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:
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:
N, then N lines.{name, qty, price} with a helper function.Enum.Enum.max_by/2, which keeps the first item when two are
equal.Read one line of text and print three lines:
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:
name xQTY = LINE_TOTAL,Items: and the sum of all quantities,Total: and the sum of all line totals,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) # 3String.pad_leading("42", 5) # " 42"
String.pad_trailing("tea", 6) # "tea "Hello thereHELLO THERE
ereht olleH
Vowels: 43
apple 3 2
bread 1 4
cheese 2 5apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese