How To Reverse String Using StringBuilder

In this blog, I am going to explain the program for string reverse using StringBuilder.

Introduction

 
In this blog, I am going to explain the program for string reverse using StringBuilder.
 
Software Requirements:
  • C# 3.0 or higher,
  • Visual Studio or Notepad
Program
  1. using System;  
  2. using System.Text;  
  3.   
  4. namespace StringReverseUsingStringBuilder {  
  5.  public static class StringReverse {  
  6.   // Reverse ExtentionMethod  
  7.   public static string Reverse(this string str) {  
  8.    // calling StringReverseUsingStringBuilder  
  9.    return Program.StringReverseUsingStringBuilder(str);  
  10.   }  
  11.  }  
  12.  class Program {  
  13.   static void Main() {  
  14.    Console.WriteLine("(Input is Optional and Default value will be CSharpcorner)");  
  15.    Console.WriteLine("Enter your data to Reverse otherwise just Hit Enter");  
  16.    string sampleText = Console.ReadLine();  
  17.    if (string.IsNullOrEmpty(sampleText))  
  18.     sampleText = "https://www.c-sharpcorner.com";  
  19.    Console.WriteLine("=======================================================");  
  20.    Console.WriteLine($ "Original Text : {sampleText}");  
  21.    Console.WriteLine("=======================================================");  
  22.    var reverseText = StringReverseUsingStringBuilder(sampleText);  
  23.    Console.WriteLine($ "Reversed Text (Using Normal Method) : {reverseText}");  
  24.    Console.WriteLine("======================================================");  
  25.    reverseText = sampleText.Reverse();  
  26.    Console.WriteLine($ "Reversed Text (Using Extension Method) : {reverseText}");  
  27.   }  
  28.   public static string StringReverseUsingStringBuilder(string str) {  
  29.    StringBuilder sb = new StringBuilder(str);  
  30.    for (int i = 0; i < sb.Length / 2; i++) {  
  31.     var temp = sb[sb.Length - i - 1];  
  32.     sb[sb.Length - i - 1] = sb[i];  
  33.     sb[i] = temp;  
  34.    }  
  35.    return sb.ToString();  
  36.   }  
  37.  }  
  38. }
If the user does not enter anything, then the default value will be "https://www.c-sharpcorner.com"
 
 
 
An example with input would be if the user enters "c-sharpcorner
 
 
 
In my next blog, we will discuss generating Random numbers without using Random Class. Thank you so much for reading my blog post.