Erlang Central

Difference between revisions of "String Reverse"

From ErlangCentral Wiki

 
(One intermediate revision by one user 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
+

Revision as of 21:50, 3 September 2006

Reversing a String by Words or Characters

Problem

You want to reverse the words or characters in a string

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,"