Erlang Central

String Check For Char

Revision as of 21:58, 18 August 2006 by Cyberlync (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


You need to find out if a string contains a character. You probably want to know the index of where the character was found.


Use the string library string:chr and string:rchr functions. string:chr searches a string for a character (starting from the left hand side of the string), and returns its index. string;rchr performs the same task, starting from the right hand side. Note that all Erlang indexes are 1-based:

1> string:chr("Hello, World!", $,).
2> string:chr("My, this is a lot of commas, I guess.", $,).
3> string:rchr("My, this is a lot of commas, I guess.", $,).

string:chr and string:rchr return 0 if no match is found:

4> string:chr("This sentence has no commas.", $,).
5> string:rchr("This sentence has no commas.", $,).