vb.net 生成随机数和字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18670847/
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
vb.net generate random number and string
提问by user2695435
I want to generate a random number of 6 intergers in vb.net which should be number and also some times alphanumerice.Like ist 4 or 5 numbers should be numbers and next should be alphnumeric.I created both numbers separatedly.like this
我想在 vb.net 中生成 6 个整数的随机数,它应该是数字,有时也是字母数字。像 4 或 5 个数字应该是数字,接下来应该是字母数字。我分别创建了两个数字。像这样
Public Function rand() As String
'Number
Dim rng As Random = New Random
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
'Alphnumeric
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 5
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
End Function
Now Any One Give Me Idea that in this function can i return number and some times string or may b a single instances which create both numbers and strings.
现在任何人给我一个想法,在这个函数中我可以返回数字和有时字符串,或者可以创建同时创建数字和字符串的单个实例。
采纳答案by Steve
The first problem to solve is the random number generator. You should use only one instance and not multiple instances that gives back the same sequence if called in short time distance. Then it is difficult to say what 'something' means in your requirements, but supposing you are fine with rougly 70% numbers and 30% a mix of numbers and strings then you call the random generator to decide for a sequence of only numbers or a mixed one. Based on the output of the random selection of the sequence build from the appropriate string
首先要解决的问题是随机数生成器。如果在短时间内调用,您应该只使用一个实例,而不是多个返回相同序列的实例。那么很难说出您的要求中的“某事”是什么意思,但是假设您可以接受大约 70% 的数字和 30% 的数字和字符串的混合,那么您可以调用随机生成器来决定仅包含数字的序列还是混合一个。基于从合适的字符串中随机选择的序列构建的输出
' A global unique random generator'
Dim rng As Random = New Random
Sub Main
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
Console.WriteLine(rand())
End Sub
Public Function rand() As String
Dim sb As New StringBuilder
' Selection of pure numbers sequence or mixed one
Dim pureNumbers = rng.Next(1,11)
if pureNumbers < 7 then
' Generate a sequence of only digits
Dim number As Integer = rng.Next(1, 1000000)
Dim digits As String = number.ToString("000000")
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, digits.Length)
sb.Append(digits.Substring(idx, 1))
Next
else
' Generate a sequence of digits and letters
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
For i As Integer = 1 To 6
Dim idx As Integer = rng.Next(0, 36)
sb.Append(s.Substring(idx, 1))
Next
End if
return sb.ToString()
End Function

