Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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 144 views
3 answers 330 views
330 views asked Jul 31, 2018 by avibootz
1 answer 143 views
143 views asked Oct 30, 2021 by avibootz
2 answers 444 views
1 answer 142 views
1 answer 162 views
162 views asked Oct 7, 2019 by avibootz
...