【问题标题】:Assign splited string to array in elixir将拆分字符串分配给长生不老药中的数组
【发布时间】:2017-01-06 08:08:42
【问题描述】:

我是长生不老药开发的新手。我在解析长生不老药中的字符串时遇到问题。假设我有字符串“Hello World from the hell”。我知道我可以像String.split("Hello World from the hell") 这样拆分它。我想知道无论如何要将此字符串的元素分配到长生不老药中?

【问题讨论】:

  • 我不太明白。你想得到什么结果?
  • 比如说 [a ,b ,c ,d, e ] = ["Hello", "World", "from", "the", "hell"]。就像在 OOP 中创建数组元素一样简单,它可以调整我输入的字符串大小的基数
  • 你的意思是像a = String.split("some string") 这样a 永远是你的字符串拆分的结果?
  • 是的。 a[i] = String.split("一些字符串").我将可以访问数组 a[i] 的元素。我知道这种方式不正确

标签: string list elixir


【解决方案1】:

String.split/1 返回 list - Elixir 的基本数据结构之一,以及 mapstuples。列表是您在 Elixir 中的首选基本集合。即使在内部它是linked list,您也可以使用Enum module 中的函数对其执行各种操作:

$ iex
iex(1)> ls = String.split("Hello World from the hell")
["Hello", "World", "from", "the", "hell"]
iex(2)> i ls
Term
  ["Hello", "World", "from", "the", "hell"]
Data type
  List
Reference modules
  List
iex(3)> Enum.take(ls, 2)
["Hello", "World"]
iex(4)> Enum.at(ls, 4)
"hell"
iex(5)> [l0, l1, l2, l3, l4] = ls
["Hello", "World", "from", "the", "hell"]
iex(6)> l4
"hell"
iex(7)> Enum.take(ls, 4) ++ ["iex", "shell"]
["Hello", "World", "from", "the", "iex", "shell"]

如您所见,Enum.at/3 为您提供类似于a[i] 样式数组访问的内容。

如果您担心在列表中查找元素的效率 - 例如,您的输入字符串将比"Hello World from the hell" 长得多,并且您将多次按索引从中获取元素,本质上每次遍历它,您都可以从中构建一个map,并通过索引有效地查看单词:

iex(8)> with_indices = Enum.with_index(ls)
[{"Hello", 0}, {"World", 1}, {"from", 2}, {"the", 3}, {"hell", 4}]
iex(9)> indices_and_words = Enum.map(with_indices, fn({a, b}) -> {b, a} end)
[{0, "Hello"}, {1, "World"}, {2, "from"}, {3, "the"}, {4, "hell"}]
iex(10)> map = Map.new(indices_and_words)
%{0 => "Hello", 1 => "World", 2 => "from", 3 => "the", 4 => "hell"}
iex(11)> map[0]
"Hello"
iex(12)> map[4]
"hell"

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2017-01-03
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多