C#

C# – Reverse Strings

Sometimes we might need to reverse string letters order. unfortunately, String class in .Net Framework up to version 3.5 doesn’t have a Reverse Method. here I will try to add Reverse Extension Method  to String class.

The idea behind string reverse is converting the string to an array of chars and then apply Array.Reverse() method and again convert the array of chars to string. see code

public string ReverseString(string originalString)
{
 char[] strArray = originalString.ToCharArray();
 Array.Reverse(strArray);
 string strReversed = new string(strArray);
 return strReversed;
}

For simplicity, StringHelper class is created to provide string.Reverse method as Extension Method

public static class StringHelper
{
 public static string ReverseString(string originalString)
 {
  char[] strArray = originalString.ToCharArray();
  Array.Reverse(strArray);
  string strReversed = new string(strArray);
  return strReversed;
 }

 public static string Reverse(this string originalString)
 {
  char[] strArray = originalString.ToCharArray();
  Array.Reverse(strArray);
  string strReversed = new string(strArray);
  return strReversed;
 }
}

Easy to use

string str = "abcdef";
string ReversedStr = str.Reverse();

Happy Coding…

Shout it kick it on DotNetKicks.com Retweet

Advertisements

2 thoughts on “C# – Reverse Strings

  1. Pingback: DotNetShoutout

Leave a Reply

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 / Change )

Twitter picture

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

Facebook photo

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

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s