SoFunction
Updated on 2025-03-06

C# generates a random string class without duplicate

This article describes the C# generation of non-repeating random string classes. Share it for your reference. The details are as follows:

This C# class is used to randomly generate non-repetitive strings. It can specify the string range and specify the length of the string to be generated.

using System;
namespace 
{
  public class RandomOperate
  {
    // 1: Randomly generate non-repeating numeric strings    private int rep = 0;
    public string GenerateCheckCodeNum(int codeCount)
    {
      string str = ;
      long num2 =  + ;
      ++;
      Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> )));
      for (int i = 0; i < codeCount; i++)
      {
        int num = ();
        str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
      }
      return str;
    }
    //Method 2: Randomly generate strings (numbers and letters are mixed)    public string GenerateCheckCode(int codeCount)
    {
      string str = ;
      long num2 =  + ;
      ++;
      Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> )));
      for (int i = 0; i < codeCount; i++)
      {
        char ch;
        int num = ();
        if ((num % 2) == 0)
        {
          ch = (char)(0x30 + ((ushort)(num % 10)));
        }
        else
        {
          ch = (char)(0x41 + ((ushort)(num % 0x1a)));
        }
        str = str + ();
      }
      return str;
    }
    #region
    /// <summary>
    /// Get randomly obtained from the string and specify a string of numbers.    /// </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 = (',');
      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)));
        }
        int t = ( - 1);
        while (temp == t)
        {
          t = ( - 1);
        }
        temp = t;
        RandomCode += allCharArray[t];
      }
      return RandomCode;
    }
    #endregion
  }
}

I hope this article will be helpful to everyone's C# programming.