- 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"
- OpenCV實例精解
- Java Web基礎與實例教程(第2版·微課版)
- Java高手真經(高級編程卷):Java Web高級開發技術
- 假如C語言是我發明的:講給孩子聽的大師編程課
- 信息技術應用基礎
- 計算機應用基礎實踐教程
- INSTANT Sinatra Starter
- CoffeeScript Application Development Cookbook
- Visual Basic 6.0程序設計實驗教程
- GameMaker Essentials
- 零基礎C#學習筆記
- Groovy 2 Cookbook
- Oracle SOA Suite 12c Administrator's Guide
- jQuery Essentials
- Python for Secret Agents