Given a string, how can I get access to its character by index? Enum.at(“my_string”, 2) doesn’t work.
Or rather, not char, but a substring of length 1, by index.
Given a string, how can I get access to its character by index? Enum.at(“my_string”, 2) doesn’t work.
Or rather, not char, but a substring of length 1, by index.
Maybe just worth noting this is quite an expensive operation since each grapheme has to be extracted up to the index. If you are processing characters in a string you may find one of these other approaches useful:
String.next_grapheme/1
is a good way to help recursing over a string’s graphemesString.graphemes/1
will decompose the string into its graphemes (each a single character string)String,to_charlist/1
will decompose the string into its code points (integer code point values)iex(37)> string = "012345"
"012345"
iex(38)> << a :: utf8, b :: utf8, c :: utf8, _rest :: binary >> = string
"012345"
iex(39)> a
48 # <- returns the code point at index 0 of the string
can I use two positions? like String.at("my_string", 2, 3)