stringvb.netchars

Selecting Characters In String


I can grab every 2 chars from sum2.text in order (102030) i get 10,20,30 but my issue is, selecting exactly those numbers 10,20,30 in order my current code below outputs: msgbox(10) msgbox(20) msgbox(30) but wont select and replace those exact numbers in order one by one

My code:

            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

my probolem is that it will show the numbers in sum2 one by one correctly, but it would select and replace at all or one by one. I believe the issue is with the selection length


Solution

  • OK, here's my attempt from what I'm understanding you are wanting to do. The problem is, you are trying to alter the string that the loop is using when you replace "10" with "a" so you need to create a variable to hold your newly built string.

        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
    

    Of course, this is only to show the workings of moving through the string and changing it. You would need to replace your selected text with the newly formatted result (fixed in this case)

    Result: ab3077328732

    Also, just so you know, if this format was such that no 2 digits would interfere, you could simply do a

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

    However if you had 2 digits like 11 next to 05 it would fail to give desired results because if would change 1105 to 1a5. Just something to think about.