C# 生成隨機字串
阿新 • • 發佈:2022-03-09
以某個字串中的隨機字元組成一定長度下的隨機字串
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static void Main(string[] args) { string retStr1; string retStr2; retStr1 = GetRandomString1("Hello World", 20); retStr2 = GetRandomString2("Hello World", 20); Console.WriteLine(retStr1); Console.WriteLine(retStr2); Console.ReadKey(); } //以chars中的字元生成length長度的隨機字串 //RNGCryptoServiceProvider為例 public static string GetRandomString1(string chars, int length) { StringBuilder sb = new StringBuilder(); RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider(); byte[] ary = new byte[8]; for (int index = 0; index < length; index++) //密碼長度為迴圈次數 { rnd.GetBytes(ary); sb.Append(chars[(int)Math.Round(Math.Abs(BitConverter.ToInt64(ary, 0)) / (decimal)long.MaxValue * (chars.Length - 1), 0)]); } return sb.ToString(); } //以chars中的字元生成length長度的隨機字串 //Random為例 public static string GetRandomString2(string chars, int length) { int charIndex; Random rnd = new Random(); StringBuilder sb = new StringBuilder(); for (int index = 0; index < length; index++) //密碼長度為迴圈次數 { charIndex = rnd.Next(chars.Length); sb.Append(chars[charIndex]); } return sb.ToString(); } } }