Example:
string str = "I am going to reverse myself.";
string strrev = "I ma gniog ot esrever .flesym"; //An easy way to achieve this
As I think I have to iterate through each word and then each letter of every word.
What I have done works fine. But I need easy/short way.
C# CODE:
string str = "I am going to reverse myself.";
string strrev = "";
foreach (var word in str.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
strrev = strrev + temp + "";
}
Console.WriteLine(strrev); //I ma gniog ot esrever .flesym
Well, here’s a LINQ solution:
If you’re using .NET 3.5, you’ll need to convert the reversed sequence to an array too:
In other words:
string(char[])constructorToArray()on the string sequence, as .NET 4 has more overloads availablestring.Joinon the result to put the reversed words back together again.Note that this way of reversing a string is somewhat cumbersome. It’s easy to create an extension method to do it:
Note that this is still “wrong” in various ways – it doesn’t cope with combining characters, surrogate pairs etc. It simply reverses the sequence of UTF-16 code units within the original string. Fine for playing around, but you need to understand why it’s not a good idea to use it for real data.