代码之家  ›  专栏  ›  技术社区  ›  alan7811

选择字符串中的字符

  •  0
  • alan7811  · 技术社区  · 7 年前

    我可以从sum2.text中抓取每2个字符,顺序是(102030),我得到10,20,30 我当前的代码如下输出:msgbox(10)MSGBoxs(20)MSGBbox(30),但不会逐个选择和替换这些精确的数字

                For i = 0 To sum2.Text.Length - 1 Step 2 'grabs every 2 chars
                Dim result = (sum2.Text.Substring(i, 2)) 'this holds the 2 chars
                MsgBox(result) 'this shows the 2 chars
                sum2.SelectionStart = i 'this starts the selection at i                                                                            
                sum2.SelectionLength = 2 'this sets the length of selection (i)                                     
                If sum2.SelectedText.Contains("10") Then 
                    sum2.SelectedText = sum2.SelectedText.Replace("10", "a")
                End If
                If sum2.SelectedText.Contains("20") Then
                    sum2.SelectedText = sum2.SelectedText.Replace("20", "b")
                End If
                If sum2.SelectedText.Contains("30") Then
                    sum2.SelectedText = sum2.SelectedText.Replace("30", "c")
                End If
    

    2 回复  |  直到 7 年前
        1
  •  0
  •   Charles May    7 年前

    好的,这是我的尝试,我理解你想要做的。问题是,当您将“10”替换为“a”时,您试图更改循环使用的字符串,因此需要创建一个变量来保存新构建的字符串。

        Dim part As String = ""
        Dim fixed As String = ""
        For i = 0 To Sum2.SelectedText.Length - 1 Step 2
            part = Sum2.SelectedText.Substring(i, 2)
            Select Case part
                Case "10"
                    part = part.Replace("10", "a")
                Case "20"
                    part = part.Replace("20", "b")
                Case "30"
                    part = part.Replace("30", "c")
            End Select
            fixed &= part
        Next
    
        Sum2.SelectedText = fixed
    

    结果:ab3077328732

    另外,正如你所知,如果这种格式是这样的,没有两个数字会干扰,你可以简单地做一个

    sub2.selectedtext.replace("10", "a").Replace("20", "b").Replace...
    

        2
  •  0
  •   Brian M Stafford    7 年前

          For i = 0 To sum2.SelectedText.Length - 1 Step 2
             MessageBox.Show(sum2.SelectedText.Substring(i, 2))
          Next