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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1546472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:28:08  来源:igfitidea点击:

Generate random strings in vb.net

vb.netrandom

提问by Cyclone

I need to generate random strings in vb.net, which must consist of (randomly chosen) letters A-Z (must be capitalized) and with random numbers interspersed. It needs to be able to generate them with a set length as well.

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

Thanks for the help, this is driving me crazy!

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

回答by JohnIdol

If you can convert this to VB.NET (which is trivial) I'd say you're good to go (if you can't, use thisor any other tool for what's worth):

如果您可以将其转换为 VB.NET(这是微不足道的),我会说您很高兴(如果不能,请使用工具或其他任何有价值的工具):

/// <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();
    }
}

Then all you've got to do is:

那么你所要做的就是:

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

回答by JCasso

Why don't you randomize a number 1 to 26 and get the relative letter.

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

Something like that:

类似的东西:

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

Edit: ChrW added.

编辑:添加了 ChrW。

Edit2: To have numbers as well

编辑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

回答by MusiGenesis

C#

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

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 

回答by ChickenMilkBomb

How about:

怎么样:

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

回答by Mun

Here's a utility class I've got to generate random passwords. It's similar to JohnIdol's Typing Monkey, but has a little more flexibility in case you want generated strings to contain uppercase, lowercase, numeric or special characters.

这是我必须生成随机密码的实用程序类。它类似于 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
}

To use it:

要使用它:

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

This code is in C# but should be fairly easy to convert to VB.NET using a code converter.

这段代码是用 C# 编写的,但使用代码转换器将其转换为 VB.NET 应该相当容易。

回答by Mike

Just be simple. for vb just do:

简单点。对于 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

This function allows for a base subset of chars to use or user can choose anything. For example you could send ABCDEF0123456789 and get random Hex. or "01" for binary.

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

回答by westonsupermare

Try this, it's the top answer already converted to VB!

试试这个,这是已经转换为 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