生成包含數字和大小寫字母的隨機碼


下面給出兩種隨機生成6為隨機碼的代碼事例:

第一:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace CreateRandom
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //定義一個包含數字,大小寫字母的字符串
13             string strAll = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
14             //定義一個結果
15             string result = "";
16             //實例化Random對象
17             Random random = new Random();
18             //使用for循環得到6為字符
19             for (int i = 0; i < 6; i++)
20             {
21                 //返回一個小於62的int類型的隨機數
22                 int rd = random.Next(62);
23                 //隨機從指定的位置開始獲取一個字符
24                 string oneChar = strAll.Substring(rd, 1);
25                 //循環加到6為
26                 result += oneChar;
27             }
28             Console.WriteLine(result);
29             Console.ReadKey();
30         }
31     }
32 }

 第二:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 隨機6位數
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Random rand = new Random();
13             StringBuilder sb = new StringBuilder();
14             for (int i = 0; i < 6; i++) 
15             {
16                 //得到一個數字
17                 int n = rand.Next(62);
18 
19                 if (n < 10)
20                 {
21                     sb.Append(n);
22                 }
23                 //得到一個大寫字母
24                 else if (n < 36)
25                 {
26                     sb.Append((char)(n + 'A' - 10));
27                 }
28                 //得到一個小寫字母
29                 else
30                 {
31                     sb.Append(Convert.ToChar(n + 'a' - 36));
32                 }
33             } 
34             string result = sb.ToString();
35             Console.WriteLine(result);
36             Console.ReadKey();
37         }
38     }
39 }

以上兩種方法大同小異,可依據自己的理解自行運用……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM