C# 生成随机字符串
以某个字符串中的随机字符组成一定长度下的随机字符串
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();
}
}
}

浙公网安备 33010602011771号