欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#生成不重复随机字符串类

程序员文章站 2023-12-04 17:46:05
本文实例讲述了c#生成不重复随机字符串类。分享给大家供大家参考。具体如下: 这个c#类用于随机产生不重复的字符串,可以指定字符串范围,可以指定要产生字符串的长度...

本文实例讲述了c#生成不重复随机字符串类。分享给大家供大家参考。具体如下:

这个c#类用于随机产生不重复的字符串,可以指定字符串范围,可以指定要产生字符串的长度

using system;
namespace dotnet.utilities
{
  public class randomoperate
  {
    // 一:随机生成不重复数字字符串 
    private int rep = 0;
    public string generatecheckcodenum(int codecount)
    {
      string str = string.empty;
      long num2 = datetime.now.ticks + this.rep;
      this.rep++;
      random random = new random(((int)(((ulong)num2) & 0xffffffffl)) | ((int)(num2 >> this.rep)));
      for (int i = 0; i < codecount; i++)
      {
        int num = random.next();
        str = str + ((char)(0x30 + ((ushort)(num % 10)))).tostring();
      }
      return str;
    }
    //方法二:随机生成字符串(数字和字母混和)
    public string generatecheckcode(int codecount)
    {
      string str = string.empty;
      long num2 = datetime.now.ticks + this.rep;
      this.rep++;
      random random = new random(((int)(((ulong)num2) & 0xffffffffl)) | ((int)(num2 >> this.rep)));
      for (int i = 0; i < codecount; i++)
      {
        char ch;
        int num = random.next();
        if ((num % 2) == 0)
        {
          ch = (char)(0x30 + ((ushort)(num % 10)));
        }
        else
        {
          ch = (char)(0x41 + ((ushort)(num % 0x1a)));
        }
        str = str + ch.tostring();
      }
      return str;
    }
    #region
    /// <summary>
    /// 从字符串里随机得到,规定个数的字符串.
    /// </summary>
    /// <param name="allchar"></param>
    /// <param name="codecount"></param>
    /// <returns></returns>
    private string getrandomcode(string allchar, int codecount)
    {
      //string allchar = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
      string[] allchararray = allchar.split(',');
      string randomcode = "";
      int temp = -1;
      random rand = new random();
      for (int i = 0; i < codecount; i++)
      {
        if (temp != -1)
        {
          rand = new random(temp * i * ((int)datetime.now.ticks));
        }
        int t = rand.next(allchararray.length - 1);
        while (temp == t)
        {
          t = rand.next(allchararray.length - 1);
        }
        temp = t;
        randomcode += allchararray[t];
      }
      return randomcode;
    }
    #endregion
  }
}

希望本文所述对大家的c#程序设计有所帮助。