String Case

From Erlang Community

(Difference between revisions)
Revision as of 21:44, 18 August 2006 (edit)
Cyberlync (Talk | contribs)

← Previous diff
Current revision (09:47, 23 November 2006) (edit) (undo)
213.171.204.166 (Talk)
(Solution)
 
(3 intermediate revisions not shown.)
Line 3: Line 3:
== Solution == == Solution ==
-Use httpd_util:to_upper or httpd_util:to_lower from the OTP httpd_util module. (Yes, I know that these would make more sense in the string module!)+For ASCII, you can do it yourself in this simple manner:
-<code> +<code>
-1> httpd_utils:to_upper("hello").+to_upper(S) -> lists:map(fun char_to_upper/1, S).
-"HELLO"+to_lower(S) -> lists:map(fun char_to_lower/1, S).
-2> httpd_utils:to_lower("ERLANG").+char_to_upper(C) when C >= $a, C =< $z -> C bxor $\s;
-"erlang"+char_to_upper(C) -> C.
 +char_to_lower(C) when C >= $A, C =< $Z -> C bxor $\s;
 +char_to_lower(C) -> C.
</code> </code>
-  
-The httpd_util module contains a dog's breakfast of functionality that probably belong in other modules, but that have not been added due to backwards-compatibility concerns.  
 +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.
-[[Category:CookBook]]+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:
 + 
 +<code>
 +-module(unicode).
 + 
 +-record(unicode_string,{encoding,language,data}).
 +</code>
 + 
 +[[Category:CookBook]][[Category:StringRecipes]]

Current revision

[edit] Problem

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

[edit] 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}).
Erlang/OTP Projects
Personal tools