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
- using System;
- using System.Text;
-
- namespace StringReverseUsingStringBuilder {
- public static class StringReverse {
-
- public static string Reverse(this string str) {
-
- return Program.StringReverseUsingStringBuilder(str);
- }
- }
- class Program {
- static void Main() {
- Console.WriteLine("(Input is Optional and Default value will be CSharpcorner)");
- Console.WriteLine("Enter your data to Reverse otherwise just Hit Enter");
- string sampleText = Console.ReadLine();
- if (string.IsNullOrEmpty(sampleText))
- sampleText = "https://www.c-sharpcorner.com";
- Console.WriteLine("=======================================================");
- Console.WriteLine($ "Original Text : {sampleText}");
- Console.WriteLine("=======================================================");
- var reverseText = StringReverseUsingStringBuilder(sampleText);
- Console.WriteLine($ "Reversed Text (Using Normal Method) : {reverseText}");
- Console.WriteLine("======================================================");
- reverseText = sampleText.Reverse();
- Console.WriteLine($ "Reversed Text (Using Extension Method) : {reverseText}");
- }
- public static string StringReverseUsingStringBuilder(string str) {
- StringBuilder sb = new StringBuilder(str);
- for (int i = 0; i < sb.Length / 2; i++) {
- var temp = sb[sb.Length - i - 1];
- sb[sb.Length - i - 1] = sb[i];
- sb[i] = temp;
- }
- return sb.ToString();
- }
- }
- }
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.