Use StringBuilder to reverse a string - CSharp Language Basics

CSharp examples for Language Basics:StringBuilder

Description

Use StringBuilder to reverse a string

Demo Code

using System;//from  ww w  .  j  a  v  a 2s .co m
using System.Text;
class MainClass
{
   public static string ReverseString(string str)
   {
      // Make sure we have a reversible string.
      if (str == null || str.Length <= 1)
      {
         return str;
      }
      StringBuilder revStr = new StringBuilder(str.Length);
      for (int count = str.Length - 1; count > -1; count--)
      {
         revStr.Append(str[count]);
      }
      return revStr.ToString();
   }
   public static void Main()
   {
      Console.WriteLine(ReverseString("Madam Im Adam"));
      Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog."));
   }
}

Result


Related Tutorials