1

我们试图仅将“a”的第一个实例替换为first second third. 然后它应该循环并将“a”的第二个实例替换为新生成的值first second third并继续这个循环,直到没有更多的“a”字符剩下并且每个“a”都是不同的值。但是输出的结果是不正确的。该代码正在擦除最后一个“a”之前的所有字符,然后替换最后一个“a”。

    Dim message As String
    Dim start As Integer = 1
    Dim letterfinder As String
    Dim timesLooped As Integer = 1
    Dim length As Integer

    Dim first As Integer
    Dim second As Integer
    Dim third As Integer
    Dim count As Integer = 1

    message = inputBox.Text
    length = Len(message)
    timesLooped = 0
  While length > timesLooped
        Dim random As New Random
        letterfinder = Mid$(message, start, 1)
        If letterfinder = "a" Then
            first = random.Next(3, 9)
            second = 1 \ first
            third = 1 - second
            outputBox.Text = Replace(message, letterfinder, first & second & third, [start], [count])
        End If
        timesLooped = timesLooped + 1
        start = start + 1
    End While
4

2 回答 2

0

您的 output.text 框只是显示最终结果(临时更改发生得太快而无法看到)。添加列表框以查看进度:

   If letterfinder = "a" Then
       first = random.Next(3, 9)
       second = 1 \ first
       third = 1 - second

       Dim res As String = Replace(message, letterfinder, _
                   first & second & third, [start], [count])
       txtOutput.Text = res
       ListBox1.Items.Add(timesLooped.ToString & vbTab & res)
   End If


Replace(message, "a", first & second & third, [start], [count]) 

在开始时返回一个子字符串 STARTING ......它不会替换并返回整个内容。第二遍的结果abaca701ca。一个列表框会告诉你。
对于ababfdsfac替换结果:

  1. 701babfdsfac
  2. 801bfdsfac
  3. 301c

你只得到当前起始值的部分

编辑

这是一个执行您想要的循环的循环。我使用了 VB6 类型的方法,因为 OP 代码比 .Net 更像那种风格

    Dim first As Integer
    Dim result As String = ""
    Dim random As New Random
    ListBox1.Items.Clear()

    For n As Integer = 1 To Len(message)
        If Mid$(message, n, 1) = "a" Then

            first = random.Next(3, 9)
            result = result & CStr(first)
            result = result & CStr(1 \ first)               ' always 0
            result = result & CStr(1 - (1 \ first))         ' always 1
        Else
            result = result & Mid$(message, n, 1)

        End If

        txtOutput.Text = result
        ListBox1.Items.Add(result)                  ' post interim results
    Next

高温高压

于 2013-09-28T01:36:07.870 回答
0
DIM randomNum = Function(i)
                  Dim r as new Random(3,9)
                  Dim num = String.Format("{0}01",r.Next().ToString)
                  Return num
                End Function

Dim output as new StringBuilder()

inputText.
    ToCharArray().
    ToList().
    ForEach(Sub(c)
              if c.equals("a"c) Then 
                  output.Append(randomNum())
              Else
                  output.Append(c)
              End If)
txtOutput.Text = output.ToString()
于 2013-09-28T02:04:30.827 回答