C # two good methods to randomly generate non-repeated strings

Source: Internet
Author: User

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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.