生成包含数字和大小写字母的随机码

下面给出两种随机生成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 }

以上两种方法大同小异,可依据自己的理解自行运用……

转载于:https://www.cnblogs.com/jeffqing/archive/2012/07/28/2612570.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值