zoukankan      html  css  js  c++  java
  • 生成包含数字和大小写字母的随机码

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

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

    因为相信,所以我去做了......
  • 相关阅读:
    设计模式之代理模式
    Java面试总结系列之Collections.sort()
    Scala基础
    Win7 电脑设置临时网络,无法加入网络;internet禁止网络共享
    Java面试题系列 提高Java I/O 性能
    电子商务中:B2C、B2B、C2B、C2C、O2O、P2P
    JVM内存格局总结
    Dubbo相关博文整理
    Java面试题汇总(一)
    Java多线程总结
  • 原文地址:https://www.cnblogs.com/jeffqing/p/2612570.html
Copyright © 2011-2022 走看看