Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 从Elixir中的字符串获取子字符串_String_Elixir - Fatal编程技术网

String 从Elixir中的字符串获取子字符串

String 从Elixir中的字符串获取子字符串,string,elixir,String,Elixir,在Ruby中,我可以: "Sergio"[1..-1] #> "ergio" 在Elixir中执行相同操作会导致运行时错误: iex(1)> "Sergio"[1..-1] ** (CompileError) iex:1: the Access syntax and calls to Access.get/2 are not available for the value: "Sergio" 还尝试: iex(1)> String.slice("Sergio", 1, -1

在Ruby中,我可以:

"Sergio"[1..-1] #> "ergio"
在Elixir中执行相同操作会导致运行时错误:

iex(1)> "Sergio"[1..-1]
** (CompileError) iex:1: the Access syntax and calls to Access.get/2 are not available for the value: "Sergio"
还尝试:

iex(1)> String.slice("Sergio", 1, -1)
** (FunctionClauseError) no function clause matching in String.slice/3
(elixir) lib/string.ex:1471: String.slice("Sergio", 1, -1)
如何从Elixir中的字符串中获取子字符串?

您可以使用:

除了
String#slice
之外,还有其他方法可以得出相同的结果:

"Sergio" |> String.split(~r|(?<=\A.)|) |> List.last |> IO.inspect
#=> "ergio"
~r|(?<=\A.).*| |> Regex.run("Sergio") |> List.last |> IO.inspect
#=> "ergio"
“Sergio”|>String.split(~r |)(?List.last |>IO.inspect
#=>“ergio”
~r |(?Regex.run(“Sergio”)|>List.last |>IO.inspect
#=>“ergio”

在这种情况下,它们不会带来任何附加值,但在一些更复杂的情况下(参考ruby的
“Sergio”[/…/]
),它们可能有一定的意义。

如果您想获得不带首字母的子字符串,还可以使用:

"Sergio" |> String.to_charlist() |> tl() |> to_string()
另一种从末尾获取子字符串的方法是:

a = "Sergio"
len = String.length(a)
String.slice(a, -len + 1, len - 1) # "ergio"
#this -len + 1 is -1(len - 1) and it's exact to Ruby's -1 when slicing string.

您的第一个方法返回的是一个字符列表而不是字符串。您希望将
|>添加到_string()
的末尾。请意识到这是一个很久以前的事实,但第二个表达式不应该是:
string.slice(“Sergio”,0..3)
(您已经有了
-3
).@OnorioCatenacci在本例中-3和3返回相同的东西。-从后面算3次,从前面算3次。
a = "Sergio"
len = String.length(a)
String.slice(a, -len + 1, len - 1) # "ergio"
#this -len + 1 is -1(len - 1) and it's exact to Ruby's -1 when slicing string.