一位朋友让我为她玩的游戏制作一个字符串随机函数。我得到了代码工作,但现在她希望每个第三个字符用短划线(或空格)分隔,但我无法让它工作。任何帮助将不胜感激。
For x As Integer = 1 To 10
strb.Append(chars(Int(Rnd() * UpperBound)))
If x Mod 2 = 0 Then
strb.Append("-")
字符需要分开,但如何防止随机字符末尾添加的短划线?
谢谢你们(和女孩们)帮助你们工作
答案 0 :(得分:2)
每隔第三个字符添加一个破折号(或其他):
For x As Integer = 1 To 5
strb.Append(chars(Int(Rnd() * UpperBound)))
If x Mod 3 = 0 Then
strb.Append("-")
End If
Next
答案 1 :(得分:1)
由于我还没有使用过那些旧的VB函数,我将向您展示如何使用VB.NET,它也可以轻松转换为C#:
Private Function RandomString(rnd As Random, size As Integer) As String
Dim chars() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim builder As New System.Text.StringBuilder()
For i As Integer = 0 To size - 1
builder.Append(chars(rnd.Next(0, chars.Length)))
Next
Return builder.ToString()
End Function
让我们生成一个包含5个字符的随机字符串:
Dim rnd = New Random()
Dim rndString = RandomString(rnd, 5)
请注意,我正在传递随机实例。如果我在方法中创建它并在循环中调用它,它将生成相同的字符串,因为Random
将使用与种子相同的时间。
编辑:我刚刚看到你需要分开结果。您可以使用重载版本:
Private Overloads Function RandomString(rnd As Random, size As Integer, separator As String, everyNChar As Int32) As String
Dim builder = New System.Text.StringBuilder()
Dim chars() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
For i As Integer = 0 To size - 1
If i > 0 AndAlso i Mod everyNChar = 0 Then
builder.Append(chars(rnd.Next(0, chars.Length))).Append(separator)
Else
builder.Append(chars(rnd.Next(0, chars.Length)))
End If
Next
Return builder.ToString()
End Function
请注意,这不会计算分隔符。
答案 2 :(得分:0)
您可以使用正则表达式替换字符串。更改正则表达式并管理变更请求将很简单:)
只需将TextBox1.Text = rndstring
替换为:
TextBox1.Text = Regex.Replace(rndstring, "[a-zA-Z0-9]{3}", "$& ")
请注意,如果尚未添加Imports System.Text.RegularExpressions
,则需要添加。{/ p>
编辑:我已经给出了上述解决方案,在每隔三个字符后插入一个“”(空格)。如果你想要一个连字符( - )只需将第二个正则表达式改为"$&-"
答案 3 :(得分:0)
如果我正确理解您,请将if语句从If x Mod 2 = 0 Then
更改为If x Mod 2 = 0 And x <> 10 Then
。这样,如果它位于最后一个元素上,它就不会附加破折号。