RandomId生成随机字符串详解实例
/*
* 名称:randomid
* 功能:生成随机id
* 作者:冰麟轻武
* 日期:2012年1月31日 03:36:28
* 版本:1.0
* 最后更新:2012年1月31日 03:36:28
*/
using system;
using system.text;
namespace blqw
{
public sealed class randomid : iformattable
{
/// <summary> 1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm
/// </summary>
public const string allwords = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm";
/// <summary> 2345678wertyuiopasdfghjkzxcvbnm23456780qwertyupasdfghjklzxcvbnm
/// </summary>
public const string simplewords = "2345678wertyuipasdfghjkzxcvbnm2345678wertyupasdfghjklzxcvbnm";
#region 私有对象
const string one = "{0}";
static randomid _rid = new randomid(0);
readonly static random _rand = new random();
static string toformat(int length)
{
stringbuilder sb = new stringbuilder(length * 3);
for (int i = 0; i < length; i++)
{
sb.append(one);
}
return sb.tostring();
}
readonly string _dict;
readonly int _rmax;
readonly string _format;
#endregion
/// <summary> 构造函数
/// </summary>
/// <param name="length">生成id长度</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-za-z</param>
public randomid(int length, string dict = allwords)
: this(randomid.toformat(length), dict)
{ }
/// <summary> 构造函数
/// </summary>
/// <param name="format">生成id格式</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-za-z</param>
public randomid(string format, string dict = allwords)
{
_dict = dict;
_format = format;
_rmax = dict.length;
}
/// <summary> 生成id
/// </summary>
public string create()
{
return string.format(_format, this);
}
/// <summary> 生成id
/// </summary>
/// <param name="length">生成id长度</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-za-z</param>
public static string create(int length, string dict = allwords)
{
return new randomid(length, dict).create();
}
/// <summary> 生成id
/// </summary>
/// <param name="format">生成id格式</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-za-z</param>
public static string create(string format, string dict = allwords)
{
return new randomid(format, dict).create();
}
#region iformattable 成员
string iformattable.tostring(string format, iformatprovider formatprovider)
{
return _dict[_rand.next(0, _rmax)].tostring();
}
#endregion
}
}
console.writeline(randomid.create(4));//使用默认字典生成4位随机字符串,默认字典中不包含l,1,o,0,q,9等容易混淆字符
console.writeline(randomid.create(4, randomid.allwords));//使用完整字典(0-9a-za-z),生成4位随机字符
console.writeline(randomid.create(10, "多少级开发和贷款撒了花费大量时间好快理发店撒娇哦就开放了的撒酒阿克里福德就是卡看了就分开的世界里分开家里的事"));//使用指定中文字典,生成4位随机字符
console.writeline(randomid.create("sn:{0}{0}{0}{0}-{0}{0}{0}-{0}{0}{0}.{0}{0}", "123456abcdef"));//使用指定字典生成特定格式的随机字符
上一篇: jdbc+jsp实现简单员工管理系统