vb.net 生成随机字符串visual basic?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14723598/
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
Generate random string visual basic?
提问by user2045852
I don't understand how to add numbers to the random string, and instead of it showing a string of like 3 sometimes, I want it to always show a string of 5 and I have no clue how to do that.
我不明白如何向随机字符串添加数字,有时它不显示类似 3 的字符串,而是希望它始终显示 5 的字符串,但我不知道该怎么做。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rndnumber As Random
Dim number As Integer
rndnumber = New Random
number = rndnumber.Next(1, 80000)
TextBox1.Text = number.ToString
End Sub
回答by Vuk Vasi?
You could use this function to create random strings:
您可以使用此函数来创建随机字符串:
Public Function GenerateRandomString(ByRef len As Integer, ByRef upper As Boolean) As String
Dim rand As New Random()
Dim allowableChars() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim final As String = String.Empty
For i As Integer = 0 To len - 1
final += allowableChars(rand.Next(allowableChars.Length - 1))
Next
Return IIf(upper, final.ToUpper(), final)
End Function
You can call this function like this:
你可以这样调用这个函数:
GenerateRandomString(5, False)
First parameter is number of characters and second is if you want upper case characters or not (True or False).
第一个参数是字符数,第二个参数是是否需要大写字符(真或假)。
回答by SysDragon
This generates a random string number of length 5:
这会生成一个长度为 5 的随机字符串数:
final = rdm.Next(0, 100000).ToString("00000")
And this function generates a random string of everything of any length:
这个函数生成一个任意长度的随机字符串:
Public Function GetRandomString(ByVal iLength As Integer) As String
Dim sResult As String = ""
Dim rdm As New Random()
For i As Integer = 1 To iLength
sResult &= ChrW(rdm.Next(32, 126))
Next
Return sResult
End Function
回答by Moises Mtz
Do you need it to be a string of numbers?, because if not, you could use System.IO.Path.GetRandomFileName. This function gives you a random uppercase string of any length, with a default of eight characters
你需要它是一串数字吗?因为如果不是,你可以使用 System.IO.Path.GetRandomFileName。此函数为您提供任意长度的随机大写字符串,默认为 8 个字符
Public Function GetRandomString(Optional ByVal iLength As Integer = 8) As String
Dim sPath, SResult As String
sPath = ""
Do
sPath = sPath + System.IO.Path.GetRandomFileName.Replace(".", "")
Loop Until sPath.Length > iLength
SResult = sPath.Substring(0, iLength)
Return SResult.ToUpper
End Function