要随机化字符串,首先使用Random类-
Random r = new Random();
现在,将Next()
方法与OrderBy()
-
string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
这是显示随机字符串的竞赛代码-
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(); } }
输出结果
String = electronics Random String = lericsecton