How to Reverse a String

Question: given a string, reverse it. You can destroy the original string or return a new string that is the reverse of the original string. For example, if input is “abcde”, output will be “edcba”.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:

   6: namespace ReverseString {

   7:

   8:     static class StringExtensions {

   9:         public static string Reverse(this string input) {

  10:             return new string(input.ToCharArray().Reverse().ToArray());

  11:         }

  12:     }

  13:

  14:     class Program {

  15:

  16:         static void ReverseString(string str) {

  17:             if (str.Length == 0)

  18:             {

  19:                 Console.WriteLine("False");

  20:                 return;

  21:             }

  22:             StringBuilder stb = new StringBuilder();

  23:

  24:             for (int i = str.Length - 1; i > -1; i--)

  25:             {

  26:                 stb.Append(str[i]);

  27:             }

  28:

  29:             Console.WriteLine("{0} => {1}", str, stb.ToString());

  30:

  31:         }

  32:

  33:         static void Main(string[] args) {

  34:

  35:

  36:             Console.WriteLine("hello world".Reverse());

  37:

  38:             ReverseString("This is a book.");

  39:

  40:             Console.WriteLine("...end");

  41:             Console.ReadLine();

  42:         }

  43:     }

  44: }

Advertisements