🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Strings

A string is text written inside double quotes. Strings can join end to end and can include values inside the text.

Join strings with <>

The <> operator places two strings end to end. Joining makes one longer string and changes neither part.

first = "Ana"
last = "Lee"
IO.puts(first <> " " <> last)
IO.puts("Elixir" <> "!")

Interpolation puts values inside text

Interpolation writes a value into a string where the #{...} marker sits. The value can be a variable or a small calculation.

name = "Ana"
score = 9
IO.puts("Hello, #{name}")
IO.puts("Score: #{score + 1}")

Characters versus bytes

The word héllo has five characters but six bytes. Plain ASCII text gives the same count both ways.

word = "héllo"
IO.puts(String.length(word))
IO.puts(byte_size(word))
IO.puts(String.length("hello"))
IO.puts(byte_size("hello"))

Example

city = "Paris"
temp = 21
message = "Weather in " <> city <> ": #{temp} degrees"
IO.puts(message)
IO.puts(String.length(city))
IO.puts(byte_size(city))

Key points

  • Quotes: strings use double quotes, like "hello".
  • Joining: the <> operator joins two strings into one longer string.
  • Interpolation: #{...} inside a string writes a value into the text at that spot.
  • Character count: String.length counts the characters a reader sees.
  • Byte count: byte_size counts the stored bytes that make up the text.

In this example, <> joins the fixed text with the city name, and interpolation places the temperature inside the message. The city name then measures five characters and five bytes.

Note

a letter with an accent can take two bytes, so its character count and byte count differ.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does String.length("héllo") return?