Today, I sorted out the source code of a previous project and found two methods to randomly generate non-repeated strings. I think it is very convenient to use them. I will post them here for future reference.
Method 1: generate a random string without repeated numbers
Copy codeThe Code is as follows:
Private int rep = 0;
/// <Summary>
/// Generate a random number string
/// </Summary>
/// <Param name = "codeCount"> Number of digits to be generated </param>
/// <Returns> the generated numeric string </returns>
Private string GenerateCheckCodeNum (int codeCount)
{
String str = string. Empty;
Long num2 = DateTime. Now. Ticks + this. rep;
This. rep ++;
Random random = new Random (int) (ulong) num2) & 0 xffffffffL) | (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;
}
Method 2: generate a random string (mixed digits and letters)
/// <Summary>
/// Generate random character strings (mixed numbers and letters)
/// </Summary>
/// <Param name = "codeCount"> Number of digits to be generated </param>
/// <Returns> generated letter string </returns>
Private string GenerateCheckCode (int codeCount)
{
String str = string. Empty;
Long num2 = DateTime. Now. Ticks + this. rep;
This. rep ++;
Random random = new Random (int) (ulong) num2) & 0 xffffffffL) | (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;
}