Erlang Central

Difference between revisions of "String Case"

From ErlangCentral Wiki

(remove httpd_util use (does this even work? I don't have this module); replace with simple ASCII solution and advice on beyond-ASCII)
(Solution)
(One intermediate revision by one user not shown)

Revision as of 09:47, 23 November 2006

Problem

You need to convert a string to all uppercase or all lowercase.

Solution

For ASCII, you can do it yourself in this simple manner:

to_upper(S) -> lists:map(fun char_to_upper/1, S).
to_lower(S) -> lists:map(fun char_to_lower/1, S).
char_to_upper(C) when C >= $a, C =< $z -> C bxor $\s;
char_to_upper(C) -> C.
char_to_lower(C) when C >= $A, C =< $Z -> C bxor $\s;
char_to_lower(C) -> C.

For many other languages where case-change makes sense, you can extend the above in a simple manner by adding new ranges or specific characters to the char_to_*/1 functions. For some, you may need extra processing in to_upper/1 or to_lower/1.

Erlang doesn't have a nice unicode-respectful way of doing this. If you'd like to prototype such a way, you might start with:

-module(unicode).

-record(unicode_string,{encoding,language,data}).