Example:
string str = \"I am going to reverse myself.\";
string strrev = \"I ma gniog ot esrever .flesym\"; //An easy way to achieve this
A
To reverse a string I use:
new String( word.Reverse().ToArray() )
The Reverse()
function is part of LINQ and works because String implements IEnumerable
. Its result is another IEnumerable
which now needs to be converted to string. You can do that by calling ToArray()
which gives a char[]
and then pass that into the constructor of string
.
So the complete code becomes:
string s="AB CD";
string reversed = String.Join(" ",
s.Split(' ')
.Select(word => new String( word.Reverse().ToArray() ) ));
Note that this code doesn't work well with certain unicode features. It has at least two problems:
char
s when UTF-16 encoded. Reversing them breaks the encoding. This is relatively easy to fix since there are just a limited number of characters initiation such a sequence(16 if I remember correctly) and this most likely won't be extended in future unicode versions.