先定義樣本字串,再隨機取index挑出字元,組成字串:
publicstaticstringRandomString(intlength)
{
stringsample="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuildersb=newStringBuilder();
varrand=newRandom(Guid.NewGuid().GetHashCode());
for(inti=1;i<=length;i++)
{
sb.Append(sample[rand.Next(0,sample.Length)]);
}
returnsb.ToString();
}
隨機產生多個ASCII數值,轉成字元,再組成字串:
字元 | ASCII | 亂數區間 |
---|---|---|
數字0-9 | 48-57 | 亂數1至10加47 |
字母A-Z | 65-90 | 亂數11至36加54 |
字母a-z | 97-122 | 亂數37至62加60 |
publicstaticstringRandomStringByAscii(intlength)
{
StringBuildersb=newStringBuilder();
varrand=newRandom(Guid.NewGuid().GetHashCode());
for(inti=1;i<=length;i++)
{
intnum=rand.Next(1,63);
//亂數1-10,對應ASCII48-57,數字0-9
if(num>=1&&num<=10)
{
num+=47;
}
//亂數11-36,對應ASCII65-90,字母A-Z
elseif(num>=11&&num<=36)
{
num+=54;
}
//亂數37-62,對應ASCII97-122,字母a-z
elseif(num>=37&&num<=62)
{
num+=60;
}
//出現其他數字一律重取ASCII48-57,數字0-9
else
{
num=rand.Next(48,58);
}
sb.Append((char)num);
}
returnsb.ToString();
}
沒有留言:
張貼留言