String Reverse

From Erlang Community

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

← Previous diff
Current revision (21:50, 3 September 2006) (edit) (undo)
Bfulgham (Talk | contribs)

 
(One intermediate revision not shown.)
Line 28: Line 28:
</code> </code>
-[[Category:CookBook]]+[[Category:CookBook]][[Category:StringRecipes]]
-Contributors +
-Based on work by GordonWeakliem and NoelWelsh. +
- +
--- BrentAFulgham - 20 Aug 2004 +
-CookbookForm+

Current revision

[edit] Reversing a String by Words or Characters

[edit] Problem

You want to reverse the words or characters in a string

[edit] Solution

In this case, you have to choose between the lists and string modules. If you intend to work only with characters, it's most efficient to use the lists module. For words, the string module is what you want, since it has ready-made functions for chunking up strings by words.

lists:reverse will reverse the characters of a string:

1> lists:reverse("Hello, World!").
"!dlroW ,olleH"

Reversing a string by words is a combination of list and string operations:

1> lists:flatmap(fun(A) -> A ++ " " end, "",
1> (lists:reverse( string:tokens("Hello, World!", " ")))).
"World! Hello, "

Obviously my simple two-line function appends an extra space on the end. You could get rid of this by doing something more complicated, such as:

1> A = lists:flatmap(fun(A) -> A ++ " " end, "",
1> (lists:reverse( string:tokens("Hello, World!", " ")))).
"World! Hello, "
2> string:substr(A, 1, length(A) - 1).
"World! Hello,"
Erlang/OTP Projects
Personal tools