Randomly rearrange a string in .NET C#
April 17, 2015 2 Comments
Say you’d like to randomly rearrange the contents of a string, i.e. put the constituent characters into new, random positions. The following method can help you with that using a combination of LINQ and Random:
private static string RearrangeString(string startingPoint) { Random num = new Random(); string rand = new string(startingPoint. OrderBy(s => (num.Next(2) % 2) == 0).ToArray()); return rand; }
Let’s test it with my name:
string myName = "Andras Nemes"; string myNewName = RearrangeString(myName);
So my new name can be something like “drsNeeAna ms” or “AdaNmesnrs e” or even “ArsNmenda es”, I haven’t decided yet.
Filip Ekberg drew my attention to the following alternative solution:
string rand = new string(startingPoint.OrderBy(x => Guid.NewGuid()).ToArray());
View the list of posts on LINQ here.
Hi Andras, interesting stuff here.
I have a question: why string.ToCharArray(), because a string is already an array of chars
Hi Luc,
You’re correct, ToCharArray is not necessary, I’ll update the post.
Thanks,
Andras