C # random generation of 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

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.