Reverse a String (now why on earth you wanna do that?)

The easiest way to reverse a string is to use the Reverse method on Array.

For example:

char[] charArr = new char[100];
charArr = "1234567890".ToCharArray();
Array.Reverse(charArr);
string reversedString = new string(charArr);

A different requirement could be to sort the string in ascending or descending order. The following code should give you a good idea on one of them (you’ll have to figure out which one it is):

...
Array.Sort(charArr, new ReversedComparer());

class ReversedComparer : IComparer
{
  public int Compare(object obj1, object obj2)
  {
    return -((IComparable) obj1).CompareTo(obj2);
  }
}

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s

Follow

Get every new post delivered to your Inbox.