C generates non repeating random string classes

  • 2020-12-26 05:52:12
  • OfStack

This article is an example of C# generating random string classes that do not repeat. Share to everybody for everybody reference. The details are as follows:

This C# class is used to randomly generate non-repeating strings, you can specify a range of strings, and you can specify the length of the string to be generated


using System;
namespace DotNet.Utilities
{
  public class RandomOperate
  {
    // 1 : Randomly generate non-repeating numeric strings  
    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;
    }
    // methods 2 : Randomly generated strings (mixed numbers and letters) 
    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>
    ///  You get a random number of strings out of a string .
    /// </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
  }
}

Hopefully this article has helped you with your C# programming.


Related articles: