在vb.net中生成随机字符串

时间:2009-10-09 23:08:14

标签: vb.net random

我需要在vb.net中生成随机字符串,该字符串必须由(随机选择的)字母A-Z(必须大写)和散布的随机数字组成。它也需要能够以一定的长度生成它们。

感谢您的帮助,这让我发疯了!

7 个答案:

答案 0 :(得分:18)

如果你可以把它转换成VB.NET(这是微不足道的)我会说你很好(如果你不能,可以使用this或任何其他工具来获得价值):< / p>

/// <summary>
/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// </summary>
/// <remarks>
/// If you try hard enough it will eventually type some Shakespeare.
/// </remarks>
class TypingMonkey
{
   private const string legalCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

   static Random random = new Random();

   /// <summary>
   /// The Typing Monkey Generates a random string with the given length.
   /// </summary>
   /// <param name="size">Size of the string</param>
   /// <returns>Random string</returns>
   public string TypeAway(int size)
   {
       StringBuilder builder = new StringBuilder();
       char ch;

       for (int i = 0; i < size; i++)
       {
           ch = legalCharacters[random.Next(0, legalCharacters.Length)];
           builder.Append(ch);
       }

       return builder.ToString();
    }
}

然后你所要做的就是:

TypingMonkey myMonkey = new TypingMonkey();
string randomStr = myMonkey.TypeAway(size);

答案 1 :(得分:4)

为什么不随机将数字1到26并获得相对的字母。

类似的东西:

Dim output As String = ""
Dim random As New Random()
For i As Integer = 0 To 9
   output += ChrW(64 + random.[Next](1, 26))
Next

编辑:ChrW补充道。

编辑2:还有数字

    Dim output As String = ""
    Dim random As New Random()

    Dim val As Integer
    For i As Integer = 0 To 9
        val = random.[Next](1, 36)
        output += ChrW(IIf(val <= 26, 64 + val, (val - 27) + 48))
    Next

答案 2 :(得分:2)

<强> C#

public string RandomString(int length)
{
    Random random = new Random();
    char[] charOutput = new char[length];
    for (int i = 0; i < length; i++)
    {
        int selector = random.Next(65, 101);
        if (selector > 90)
        {
            selector -= 43;
        }
        charOutput[i] = Convert.ToChar(selector);
    }
    return new string(charOutput);
}

<强> VB.Net

Public Function RandomString(ByVal length As Integer) As String 
    Dim random As New Random() 
    Dim charOutput As Char() = New Char(length - 1) {} 
    For i As Integer = 0 To length - 1 
        Dim selector As Integer = random.[Next](65, 101) 
        If selector > 90 Then 
            selector -= 43 
        End If 
        charOutput(i) = Convert.ToChar(selector) 
    Next 
    Return New String(charOutput) 
End Function 

答案 3 :(得分:2)

怎么样:

Private Function GenerateString(len as integer) as String
        Dim stringToReturn as String=""
        While stringToReturn.Length<len
           stringToReturn&= Guid.NewGuid.ToString().replace("-","")
        End While
        Return left(Guid.NewGuid.ToString(),len)
End Sub

答案 4 :(得分:1)

这是我必须生成随机密码的实用程序类。它与JohnIdol的Typing Monkey类似,但如果您希望生成的字符串包含大写,小写,数字或特殊字符,则会更灵活。

public static class RandomStringGenerator
{
    private static bool m_UseSpecialChars = false;

    #region Private Variables

    private const int m_MinimumLength = 8;
    private const string m_LowercaseChars = "abcdefghijklmnopqrstuvqxyz";
    private const string m_UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string m_NumericChars = "123456890";
    private const string m_SpecialChars = "~?/@#!£$%^&*+-_.=|";

    #endregion

    #region Public Methods

    /// <summary>
    /// Generates string of the minimum length
    /// </summary>
    public static string Generate()
    {
        return Generate(m_MinimumLength);
    }

    /// <summary>
    /// Generates a string of the specified length
    /// </summary>
    /// <param name="length">The number of characters to generate</param>
    public static string Generate(int length)
    {
        return Generate(length, Environment.TickCount);
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Generates a string of the specified length using the specified seed
    /// </summary>
    private static string Generate(int length, int seed)
    {
        // Generated strings must contain at least 3 of the following character groups: uppercase letters, lowercase letters
        // numerals, and special characters (!, #, $, £, etc)

        // The generated string must be at least 4 characters  so that we can add a single character from each group.
        if (length < 4) throw new ArgumentException("String length must be at least 4 characters");

        StringBuilder SB = new StringBuilder();

        Random rand = new Random(seed);

        // Ensure that we add all of the required groups first
        SB.Append(GetRandomCharacter(m_LowercaseChars, rand));
        SB.Append(GetRandomCharacter(m_UppercaseChars, rand));
        SB.Append(GetRandomCharacter(m_NumericChars, rand));

        if (m_UseSpecialChars)
            SB.Append(GetRandomCharacter(m_SpecialChars, rand));

        // Now add random characters up to the end of the string
        while (SB.Length < length)
        {
            SB.Append(GetRandomCharacter(GetRandomString(rand), rand));
        }

        return SB.ToString();
    }

    private static string GetRandomString(Random rand)
    {
        int a = rand.Next(3);
        switch (a)
        {
            case 1:
                return m_UppercaseChars;
            case 2:
                return m_NumericChars;
            case 3:
                return (m_UseSpecialChars) ? m_SpecialChars : m_LowercaseChars;
            default:
                return m_LowercaseChars;
        }
    }

    private static char GetRandomCharacter(string s, Random rand)
    {
        int x = rand.Next(s.Length);

        string a = s.Substring(x, 1);
        char b = Convert.ToChar(a);

        return (b);
    }

    #endregion
}

使用它:

string a = RandomStringGenerator.Generate();   // Generate 8 character random string
string b = RandomStringGenerator.Generate(10); // Generate 10 character random string

此代码在C#中,但使用code converter转换为VB.NET相当容易。

答案 5 :(得分:0)

简单一点。对于vb,请执行:

Public Function RandomString(size As Integer, Optional validchars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz") As String
    If size < 1 Or validchars.Length = 0 Then Return ""
    RandomString = ""
    Randomize()
    For i = 1 To size
        RandomString &= Mid(validchars, Int(Rnd() * validchars.Length) + 1, 1)
    Next
End Function

此功能允许使用字符的基本子集,或者用户可以选择任何内容。例如,您可以发送ABCDEF0123456789并获得随机Hex。或“01”表示二进制。

答案 6 :(得分:0)

试试这个,这是已经转换为VB的最佳答案!

Private Function randomStringGenerator(size As Integer)
    Dim random As Random = New Random()
    Dim builder As Text.StringBuilder = New Text.StringBuilder()
    Dim ch As Char
    Dim legalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"

    For cntr As Integer = 0 To size
        ch = legalCharacters.Substring(random.Next(0, legalCharacters.Length), 1)
        builder.Append(ch)
    Next
    Return builder.ToString()
End Function