Get a char from a string by index

Given a string, how can I get access to its character by index?“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:

  1. String.next_grapheme/1 is a good way to help recursing over a string’s graphemes
  2. String.graphemes/1 will decompose the string into its graphemes (each a single character string)
  3. String,to_charlist/1 will decompose the string into its code points (integer code point values)
  4. Binary pattern matching may be good if you know the index you want is in a constant place, for example:
iex(37)> string = "012345"                                              
iex(38)> << a :: utf8, b :: utf8, c :: utf8, _rest :: binary >> = string
iex(39)> a
48  # <- returns the code point at index 0 of the string

can I use two positions? like"my_string", 2, 3)

In this case use String.slice/2, for example:

iex> String.slice("elixir", 2..3)