C#自界說函數NetxtString生成隨機字符串。本站提示廣大學習愛好者:(C#自界說函數NetxtString生成隨機字符串)文章只能為提供參考,不一定能成為您想要的結果。以下是C#自界說函數NetxtString生成隨機字符串正文
本文實例展現了C#自界說函數NetxtString完成生成隨機字符串的辦法,在停止C#項目開辟中異常適用!分享給年夜家供年夜家參考。
1、生成隨機字符串
症結代碼以下:
/// <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(); } }
測試成果以下圖所示:
2、依據指定字符生成隨機字符串
症結代碼以下:
/// <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#進修可以或許有所贊助!