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 }

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

    因为相信,所以我去做了......
  • 相关阅读:
    lintcode:Binary Search 二分查找
    lintcode:1-10题
    leetcode 5 :Longest Palindromic Substring 找出最长回文子串
    leetcode 4 : Median of Two Sorted Arrays 找出两个数组的中位数
    Project Euler 78:Coin partitions
    Project Euler 77:Prime summations
    Project Euler 76:Counting summations
    筛选法求素数
    Codeforces D546:Soldier and Number Game
    Project Euler 75:Singular integer right triangles
  • 原文地址:https://www.cnblogs.com/jeffqing/p/2612570.html
Copyright © 2011-2022 走看看