- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 432字
- 2021-08-05 10:42:45
Strings and charlists
Strings are binaries with UTF-8 codepoints in them. You create a string with the usual double-quote syntax:
iex> "hey, a string"
"hey, a string"
Charlists are, as the name implies, lists of character codes. You create them using the single-quote syntax:
iex> 'hey, a charlist'
'hey, a charlist'
Since this is just a list, you can use the hd function to get the code for the first character:
iex> hd('hey, a charlist')
104
Both representations support string interpolation:
iex> "two plus two is: #{2+2}"
"two plus two is: 4"
iex> 'four minus one is: #{4-1}'
'four minus one is: 3'
Both representations also support the heredoc notation, which is most commonly used to write documentation. To create it, use three single or double quotes:
iex> """
...> a string with heredoc notation
...> """
"a string with heredoc notation\n"
iex> '''
...> a charlist with heredoc notation
...> '''
'a charlist with heredoc notation\n'
Elixir provides sigils as another syntax to declare strings or charlists, which can be handy if you want to include quotes inside your string. You can use ~s to create a string and ~c to create a charlist (their uppercase versions, ~S and ~C, are similar but don't interpolate or escape characters):
iex> ~s(a string created by a sigil)
"a string created by a sigil"
iex> ~c(a charlist created by a sigil)
'a charlist created by a sigil'
There's another sigil that's worth mentioning: ~r, which is used for regular expressions. In the next snippet, we're using the run function from the Regex module to exemplify the usage of the ~r sigil:
iex> Regex.run(~r{str}, "a string")
["str"]
iex> Regex.run(~r{123}, "a string")
nil
You can find the list of supported sigils (and also how to create your own!) at http://elixir-lang.github.io/getting-started/sigils.html.
The convention in the Elixir community is to only use the term string when referring to the double-quote format. This distinction is important, since their implementation is very different. Functions from the String module will only work on the double-quote format. You should always use the double-quote format, unless you're required to use a charlist—which is the case, for instance, when you're using Erlang libraries. You can use the following functions to convert between the two formats:
iex> String.to_charlist("converting to charlist")
'converting to charlist'
iex> List.to_string('converting to string')
"converting to string"
- 手機安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- Spring 5企業(yè)級開發(fā)實戰(zhàn)
- Fundamentals of Linux
- Java程序設(shè)計與實踐教程(第2版)
- 深入RabbitMQ
- SQL Server從入門到精通(第3版)
- Nginx Lua開發(fā)實戰(zhàn)
- ExtJS高級程序設(shè)計
- NGINX Cookbook
- Python+Tableau數(shù)據(jù)可視化之美
- HTML+CSS+JavaScript網(wǎng)頁制作:從入門到精通(第4版)
- 計算機應(yīng)用基礎(chǔ)(第二版)
- TypeScript圖形渲染實戰(zhàn):2D架構(gòu)設(shè)計與實現(xiàn)
- C語言程序設(shè)計與應(yīng)用實驗指導書(第2版)
- JavaScript Concurrency