2

一位朋友让我为她玩的游戏制作一个字符串随机化器。我让代码工作了,但现在她想让字符每隔三个字符用破折号(或空格)分隔,但我无法让它工作。任何帮助将不胜感激。

            For x As Integer = 1 To 10
                  strb.Append(chars(Int(Rnd() * UpperBound)))
          If x Mod 2 = 0 Then 
          strb.Append("-")

字符需要分开,但是如何防止在随机字符末尾添加破折号?

感谢伙计们(和女孩们)的帮助,它正在工作

4

4 回答 4

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
于 2012-04-20T11:59:17.070 回答
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

请注意,这不会计算分隔符。

于 2012-04-20T12:08:09.020 回答
0

您可以使用正则表达式来替换字符串。更改正则表达式和管理更改请求将很简单:)

只需替换TextBox1.Text = rndstring为:

TextBox1.Text = Regex.Replace(rndstring, "[a-zA-Z0-9]{3}", "$& ")

Imports System.Text.RegularExpressions请注意,如果尚未完成,您需要添加。

编辑:我已经给出了上述解决方案,在每三个字符之后插入一个“”(空格)。如果您想要连字符 (-),只需将第二个正则表达式更改为"$&-"

于 2012-04-20T12:23:24.173 回答
0

如果我对您的理解正确,请将 if 语句从 更改If x Mod 2 = 0 ThenIf x Mod 2 = 0 And x <> 10 Then。这样,如果它在最后一个元素上,它就不会附加破折号。

于 2012-04-21T04:31:16.213 回答