
正文
C#生成随机字符串(数字,字母,特殊符号)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//int number;
//int count = 7;
//string checkCode = String.Empty; //存放随机码的字符串 //System.Random random = new Random(); //for (int i = 0; i < count; i++) //产生7位校验码
//{
// number = random.Next();
// number = number % 36;
// if (number < 10)
// {
// number += 48; //数字0-9编码在48-57
// }
// else
// {
// number += 55; //字母A-Z编码在65-90
// } // checkCode += ((char)number).ToString();
//}
//Console.WriteLine(checkCode);
Program p = new Program();
bool booNumber = true;
bool booSign = true;
bool booSmallword = true;
bool booBigword = true;
//p.getRandomizer(7, booNumber, booSign, booSmallword, booBigword);
Console.WriteLine(p.getRandomizer(, booNumber, booSign, booSmallword, booBigword));
Console.ReadLine();
}
public string getRandomizer(int intLength, bool booNumber, bool booSign, bool booSmallword, bool booBigword)
{
//定义
Random ranA = new Random();
int intResultRound = ;
int intA = ;
string strB = "";
while (intResultRound < intLength)
{
//生成随机数A,表示生成类型
//1=数字,2=符号,3=小写字母,4=大写字母
intA = ranA.Next(, );
//如果随机数A=1,则运行生成数字
//生成随机数A,范围在0-10
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == && booNumber)
{
intA = ranA.Next(, );
strB = intA.ToString() + strB;
intResultRound = intResultRound + ;
continue;
}
//如果随机数A=2,则运行生成符号
//生成随机数A,表示生成值域
//1:33-47值域,2:58-64值域,3:91-96值域,4:123-126值域
if (intA == && booSign == true)
{
intA = ranA.Next(, );
//如果A=1
//生成随机数A,33-47的Ascii码
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == )
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
} //如果A=2
//生成随机数A,58-64的Ascii码
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == )
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
} //如果A=3
//生成随机数A,91-96的Ascii码
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == )
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
} //如果A=4
//生成随机数A,123-126的Ascii码
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == )
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
}
} //如果随机数A=3,则运行生成小写字母
//生成随机数A,范围在97-122
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == && booSmallword == true)
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
} //如果随机数A=4,则运行生成大写字母
//生成随机数A,范围在65-90
//把随机数A,转成字符
//生成完,位数+1,字符串累加,结束本次循环
if (intA == && booBigword == true)
{
intA = ranA.Next(, );
strB = ((char)intA).ToString() + strB;
intResultRound = intResultRound + ;
continue;
}
}
return strB;
}
}
}








