我有一个聊天系统,我想放一个"随机字符串生成器"。
在我的聊天中,我必须写"%random%"它将替换为随机字符串。
我有一个问题,如果我输入"%random %% random %% random%"例如,它将生成相同的字符串3次。
•这是我的功能:
Public Function getRandomString(ByVal len As Integer) As String
Randomize()
Dim stringMap as string = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
Dim rnd As New Random()
For i As Integer = 0 To len - 1
Randomize()
rndString &= stringMap.Substring(rnd.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
•这是我的函数调用:
Dim msg As String = "Random string: %random%%random%%random%"
msg = msg.Replace("%random%", getRandomString(8))
MsgBox(msg)
输出例如:随机字符串:5z15if725z15if725z15if72
我想这是因为它将第一个返回值保留在内存中并粘贴它,我该如何解决?
我必须自己创建一个string.replace函数吗?感谢
答案 0 :(得分:1)
哦不!你根本不应该在这里打电话给Randomize()
! Random与VB的Rnd()
函数结合使用。在这里创建一个新的Random对象就足够了
每次获得相同结果的原因是因为您每次都在创建一个新的Random。您应该重复使用相同的对象来获得不同的结果。
'Create the object once
Private Shared rnd As New Random()
Public Function getRandomString(ByVal len As Integer) As String
Dim stringMap as string = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
For i As Integer = 0 To len - 1
rndString &= stringMap.Substring(rnd.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
编辑:我意识到除了上述更改之外,还需要为每个"%random%"
调用getRandomString函数。 String.Replace
只调用一次函数并将结果粘贴到任何地方。使用Regex,您可以执行以下操作:
msg = new Regex("%random%").Replace(input, Function (match) getRandomString(8))
答案 1 :(得分:0)
一种简单的方法是找到第一次出现的“%random%”,替换它,然后根据需要重复。
作为控制台应用程序编写:
Option Infer On
Module Module1
Dim rand As New Random
Public Function getRandomString(ByVal len As Integer) As String
Dim stringMap As String = "abcdefghijklmnopqrstuwvxyz0123456789"
Dim rndString As String = ""
For i As Integer = 0 To len - 1
rndString &= stringMap.Substring(rand.Next(0, stringMap.Length), 1)
Next
Return rndString
End Function
Function ReplaceRandoms(s As String) As String
Dim stringToReplace = "%random%"
Dim r = s.IndexOf(stringToReplace)
While r >= 0
s = s.Remove(r, stringToReplace.Length).Insert(r, getRandomString(stringToReplace.Length))
r = s.IndexOf(stringToReplace)
End While
Return s
End Function
Sub Main()
Dim msg As String = "Random string: %random%%random%%random%"
msg = ReplaceRandoms(msg)
Console.WriteLine(msg)
Console.ReadLine()
End Sub
End Module