BuddyRoach
BuddyRoach

Reputation: 162

Replacing Characters in an Array in VB.NET

I am trying to create a deciphering program which takes the entire English alphabet and shifts the letters' positioning to the left at one increment at a time. I have created a character array for this and I have got the shifting part to work. So, the index of each character in the array changes each time a shift is made. I also created an identical character array which does not shift so it has something to compare to.

Once the shift is made, I have textbox1 output into textbox2 which replaces the letters to their now corresponding letters based on the index of the first character array. For instance, "ABC" is now "DEF". The problem I am having is upon replacing the characters, it will replace them again because their state was changed previously. For example, I changed "A" to "B". Then I move on to changing "B" to "C". But since the "A" was changed to a "B", it is changed again to a "C". I realize doing a For Each Loop caused this to happen so I took it out of a loop and it still does it. I even tried putting a break in the code such as GOTO but that just stops the loop after changing the first letter.

Here is my code:

Private Sub cryptshift()
    'SHIFTING ALL CHARACTERS IN ARRAY ONE SPACE TO THE LEFT
    Dim temporaryStorageA As [String] = charArray(0)
    Dim temporaryStorageB As [String]() = New [String](charArray.Length - 1) {}

    For i As Integer = 1 To charArray.Length - 1
        temporaryStorageB(i - 1) = charArray(i)
        charArray(i - 1) = temporaryStorageB(i - 1)
    Next
    charArray(charArray.Length - 1) = temporaryStorageA

    'CLEARING LABEL54 AND REALIGNING ARRAY TO LABEL53
    Label54.Text = Nothing
    For Each c In charArray
        Label54.Text = Label54.Text & c & "-"
    Next

    'DECIPHERING
    Dim mess As String = TextBox1.Text
    Dim result As String = ""
    For i As Integer = 0 To mess.Length - 1
        Dim c As Char = mess(i)
        Dim itemindex As Integer = Array.IndexOf(charArray2, c)

    '**This IF Statement allows letters to be deciphered but also allows other characters such as punctuation, numbers and spaces to go through without any altering.**
        If charArray2.Contains(c) Then
            result &= charArray(itemindex)
        Else
            result &= c
        End If

    Next
    TextBox2.Text = result


End Sub

Upvotes: 0

Views: 2093

Answers (1)

the_lotus
the_lotus

Reputation: 12748

Your problem is the .Replace. You should change only the current character. Here, I'm creating a new string with the result.

Dim mess As String = TextBox1.Text
Dim result As String = ""
For i As Integer = 0 To mess.length-1
    Dim c As Char = mess(I)
    Dim itemindex As Integer = Array.IndexOf(charArray2, c)
    result &= charArray(itemindex)
Next

You could then use a string building.

Upvotes: 1

Related Questions