Reputation: 5251
In Ruby, I can easily get nth element of a string by "Hello"[0] #=> "H"
.
I am aware of String.slice/3
in Elixir and I can do it this way: String.slice("Hello", 0..0)
. This method seems a little verbose though, is there a shorter way to get nth element of string in Elixir?
Upvotes: 2
Views: 1129
Reputation: 222108
To get the nth grapheme as a String, you can use String.at/2
:
iex(1)> String.at "hello", 2
"l"
iex(2)> String.at "πr²", 2
"²"
To get the nth byte as an integer, you can use :binary.at/2
:
iex(3)> :binary.at "hello", 2
108
iex(4)> <<108>>
"l"
iex(5)> :binary.at "πr²", 2
114
iex(6)> <<114>>
"r"
Upvotes: 5