how to get char index in string with Elixir ?

1,527 views
Skip to first unread message

fx

unread,
Jun 27, 2014, 5:00:35 AM6/27/14
to elixir-l...@googlegroups.com


I wan to find char index in string , and I found Erlang have function 

    chr(String, Character) -> Index

I try call chr function in Elixir 

iex(18)> a = "abc"
"abc"
iex(19)> :string.chr(a, "b")
** (FunctionClauseError) no function clause matching in :string.chr/2
    (stdlib) string.erl:96: :string.chr("abc", "b")
iex(19)> :string.chr(a, ?b) 
** (FunctionClauseError) no function clause matching in :string.chr/3
    (stdlib) string.erl:98: :string.chr("abc", 98, 1)
iex(19)> 

 
my question is how to represent a Character in ELixir ? or Have any function like erlang chr in ELixir ?



Eduardo Gurgel

unread,
Jun 27, 2014, 5:15:41 AM6/27/14
to elixir-l...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


There are some concepts here:

Notice the double/single quotes

Strings = 'I am a erlang string'
Erlang binaries = "I am a erlang binary"

A char is represented using ?, In your case:

iex> :string.chr('abc', ?b)
2

Any library on Erlang will run on Elixir. The error you had happened just because of the data types you passed.

More information on the basic data types: http://elixir-lang.org/getting_started/2.html

Regards,

Eduardo

Eduardo Gurgel

unread,
Jun 27, 2014, 5:19:54 AM6/27/14
to elixir-l...@googlegroups.com
In time: also take a look this chapter too: http://elixir-lang.org/getting_started/6.html
--
Eduardo

Eric Meadows-Jönsson

unread,
Jun 27, 2014, 5:37:26 AM6/27/14
to elixir-l...@googlegroups.com
Use `:binary.match` to find the index of a character in a string. `:binary.match("string", "t")` returns `{3, 1}`, 3 being the index and 1 being the length of the match. Keep in mind that it doesn't return the Nth character, only the Nth byte, characters may span multiple bytes.
--
Eric Meadows-Jönsson
Reply all
Reply to author
Forward
0 new messages