Randomize string in C#


To randomize string, firstly use Random class −

Random r = new Random();

Now, use the Next() method with OrderBy() −

string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());

Here is the compete code that displays randomize string −

Example

 Live Demo

using System;
using System.IO;
using System.Linq;
class Demo {
   static void Main() {
      const string str = "electronics";
      Random r = new Random();
      string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
      Console.WriteLine("String = {0}", str);
      Console.WriteLine("Random String = {0}",random);
      Console.Read();
   }
}

Output

String = electronics
Random String = lericsecton

Updated on: 22-Jun-2020

923 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements