C#自定义函数NetxtString生成随机字符串
程序员文章站
2023-12-17 12:05:28
本文实例展示了c#自定义函数netxtstring实现生成随机字符串的方法,在进行c#项目开发中非常实用!分享给大家供大家参考。
一、生成随机字符串
关键代码如下:...
本文实例展示了c#自定义函数netxtstring实现生成随机字符串的方法,在进行c#项目开发中非常实用!分享给大家供大家参考。
一、生成随机字符串
关键代码如下:
/// <summary> /// 生成随机字符串 /// </summary> /// <param name="random">random</param> /// <param name="size">字符串长度</param> /// <param name="lowercase">字符串是小写</param> /// <returns>随机字符串</returns> public static string netxtstring(this random random, int size, bool lowercase) { stringbuilder _builder = new stringbuilder(size); int _startchar = lowercase ? 97 : 65;//65 = a / 97 = a for (int i = 0; i < size; i++) _builder.append((char)(26 * random.nextdouble() + _startchar)); return _builder.tostring(); }
测试代码如下:
static void main(string[] args) { try { random _random = new random(); for (int i = 0; i < 10; i++) { console.writeline(_random.netxtstring(4, false)); } } catch (exception ex) { console.writeline(ex.message); } finally { console.readline(); } }
测试结果如下图所示:
二、根据指定字符生成随机字符串
关键代码如下:
/// <summary> /// 0~9 a~z字符串 /// </summary> public static string randomstring_09az = "0123456789abcdefghijkmlnopqrstuvwxyz"; /// <summary> /// 依据指定字符串来生成随机字符串 /// </summary> /// <param name="random">random</param> /// <param name="randomstring">指定字符串</param> /// <param name="size">字符串长度</param> /// <param name="lowercase">字符串是小写</param> /// <returns>随机字符串</returns> public static string netxtstring(this random random, string randomstring, int size, bool lowercase) { string _nextstring = string.empty; if (random != null && !string.isnullorempty(randomstring)) { stringbuilder _builder = new stringbuilder(size); int _maxcount = randomstring.length - 1; for (int i = 0; i < size; i++) { int _number = random.next(0, _maxcount); _builder.append(randomstring[_number]); } _nextstring = _builder.tostring(); } return lowercase ? _nextstring.tolower() : _nextstring.toupper(); }
测试代码如下:
static void main(string[] args) { try { random _random = new random(); string _ramdomstring = randomtoolv2.randomstring_09az; for (int i = 0; i < 20; i++) { // console.writeline(_random.netxtstring(4, false)); console.writeline(_random.netxtstring(_ramdomstring, 4, false)); } } catch (exception ex) { console.writeline(ex.message); } finally { console.readline(); } }
代码运行效果如下图所示:
希望本文所述实例对大家的c#学习能够有所帮助!