How to random (shuffle) a string in C#

2 Answers

0 votes
using System;
using System.Linq;

public class ShuffleString_CSharp
{
    public static void Main(string[] args)
    {
        const string str = "Obi-Wan Kenobi, You\'re my only hope";
 
        Random num = new Random();
 
        string rand_str = new string(str.ToCharArray().
                                     OrderBy(s => (num.Next(5) % 2) == 0).
                                     ToArray());
 
        Console.WriteLine(rand_str);
    }
}

 
 
/*
run:
    
b-W i Yu opeOianKenob,o'remy only h
  
*/

 



answered Aug 25, 2018 by avibootz
edited Nov 4, 2024 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static Random _random = new Random();

        // Fisher-Yates shuffle
        static string Shuffle<T>(T[] array)
        {
            int n = array.Length;
            for (int i = 0; i < n; i++)
            {
                int rand = i + _random.Next(n - i);
                T temp = array[rand];
                array[rand] = array[i];
                array[i] = temp;
            }

            return string.Join("", array);
        }
        static void Main()
        {
            const string str = "Obi-Wan Kenobi, You’re my only hope";

            string rand_str = Shuffle(str.ToCharArray());

            Console.WriteLine(rand_str);
        }
    }
}


/*
run:
   
 Who  b'biaeoe-yon,rKnloYup i yeOmn
 
*/

 



answered Aug 25, 2018 by avibootz

Related questions

1 answer 161 views
3 answers 371 views
371 views asked Jul 31, 2018 by avibootz
1 answer 169 views
169 views asked Oct 30, 2021 by avibootz
2 answers 513 views
1 answer 166 views
1 answer 186 views
186 views asked Oct 7, 2019 by avibootz
...