Difference between revisions of "String Reverse"
From ErlangCentral Wiki
|Line 28:||Line 28:|
Revision as of 21:50, 3 September 2006
Reversing a String by Words or Characters
You want to reverse the words or characters in a string
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,"