Shuffle string c#

ksmakkapawee picture ksmakkapawee · Jan 19, 2011 · Viewed 25.5k times · Source

I want to know shuffle string

Example string

string word;

//I want to shuffle it
word = "hello"  

I would be able to get:

rand == "ohlel"
rand == "lleho"
etc.

Answer

nan picture nan · Jan 19, 2011

This solution (in a form of extension method) is nice:

    public static string  Shuffle(this string str)
    {
        char[] array = str.ToCharArray();
        Random rng = new Random();
        int n = array.Length;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            var value = array[k];
            array[k] = array[n];
            array[n] = value;
        }
        return new string(array);
    }