A nifty question on how to reverse strings using c#.

Now I could have used the built in fuction of .reverse(), but then how would that show off my skillsets. ;)

Execute here: https://dotnetfiddle.net/FV8fFv

using System;
using System.Text;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var str = "Hello World!";
        var arr = str.ToCharArray(); //Reset Data        
        NormalWay(arr);

        arr = str.ToCharArray(); //Reset Data
        ForLoop(arr);
        
        arr = str.ToCharArray(); //Reset Data
        ForEachStack(arr);
    }
    
    private static void NormalWay(char[] data){
        Console.WriteLine("\nNormal Way.");
        Array.Reverse(data);
        Console.WriteLine(data);
    }
    
    private static void ForLoop(char[] data){
        Console.WriteLine("\nUsing String Builder and a for loop.");
        var sb = new StringBuilder();
        for(var i = data.Length - 1 ; i >= 0 ; i--)
        {
            sb.Append(data[i]);

        }
        Console.WriteLine(sb.ToString());
    }
    
    private static void ForEachStack(char[] data){
        Console.WriteLine("\nUsing a stack and a foreach loop.");
        var stk = new Stack<char>();
        foreach(var n in data)
            stk.Push(n);
        
        Console.WriteLine(stk.ToArray());
    }
}
Advertisements
This entry was posted in Brian's Code Extreme, C# and tagged , . Bookmark the permalink.

One Response to A nifty question on how to reverse strings using c#.

  1. dineshramitc says:

    Reblogged this on Dinesh Ram Kali..

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