TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Randomize Chars in String

This C# article shows how to randomize strings with LINQ. It discusses the problems with this approach.

Randomize chars in string.

This method randomly rearranges the letters in a string. It shuffles the letters for a word game or other simple application. It can help find new hash codes from the same string. This implementation can be adapted to other problems.

Example. First, this solution uses LINQ and the method syntax. This is not a cryptographic or casino-quality algorithm, but for quick applications, it works great. It uses OrderBy along with the new string constructor.

Random Number

C# program that randomizes strings

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// The source string
	const string original = "senators";

	// The random number sequence
	Random num = new Random();

	// Create new string from the reordered char array
	string rand = new string(original.ToCharArray().
	    OrderBy(s => (num.Next(2) % 2) == 0).ToArray());

	// Write results
	Console.WriteLine("original: {0}\r\nrand: {1}",
	    original,
	    rand);
	Console.Read();
    }
}

Output

original: senators
rand: tossenar

We see that char arrays are enumerable, meaning when you apply foreach or OrderBy, you individually get each letter. This is just what we need. This is the LINQ method syntax, which combines the OrderBy with a lambda expression.

OrderByLambda Expression

Also: You could use the query syntax instead. This is clearer in some program contexts.

LINQ

Finally: ToArray converts the enumerable letters in the statement to a string again, producing the final result: a randomized string.

ToArrayString Constructor

Summary. We used OrderBy to randomize the characters in a string. This style of code could be used in much more serious systems. It is interesting to experiment with, but also has some drawbacks—it does not randomize as well as other algorithms.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf