Reputation: 677
i've been trying to figure this out for the last hour, i almost got it to work, but it just displays the word un-reversed. I don't know why this is. I know its a beginner question but please help. Thanks.
Private Sub btnReverse_Click(sender As Object, e As EventArgs) Handles btnReverse.Click
Dim strInput As String
Dim strLetter As String
Dim intLength As Integer
strInput = txtWord.Text
intLength = strInput.Length
'!!de-incremented because index starts at 0!!
intLength = intLength - 1
Dim indexReverse As Integer = intLength
For index As Integer = 0 To intLength Step +1
'get letter at this index
strLetter = strInput.Substring(index, 1)
'remove letter just got
strInput = strInput.Remove(index, 1)
'insert new letter at old letter place
strInput = strInput.Insert(indexReverse, strLetter)
indexReverse = indexReverse - 1
Next
lblReverse.Text = strInput
End Sub
Ok so i edited my code as per kjtl's idea, now im getting an argumentoutofrange exeption. I know what that means but i dont understand why im getting that exeption. To reiterate, i want to Edit this code as little as possible to get it to work. Both ideas were easier ways of doing this, i just want to fix my code without replacing it all for educational purposes.
Private Sub btnReverse_Click(sender As Object, e As EventArgs) Handles btnReverse.Click
Dim strInput As String
Dim strOutput As String = ""
Dim strLetter As String
Dim intLength As Integer
Dim chrPadding As Char = Convert.ToChar(" ")
strInput = txtWord.Text
intLength = strInput.Length
'!!de-incremented because index starts at 0!!
intLength = intLength - 1
Dim indexReverse As Integer = intLength
For index As Integer = 0 To intLength Step +1
'get letter at this index
strLetter = strInput.Substring(index, 1)
'assign temp values to strOutput
strOutput = strOutput.PadRight(intLength, chrPadding)
'remove letter just got
strOutput = strOutput.Remove(index, 1)
'insert new letter at old letter place
strOutput = strOutput.Insert(indexReverse, strLetter)
indexReverse = indexReverse - 1
Next
lblReverse.Text = strInput
End Sub
Upvotes: 1
Views: 1425
Reputation: 216293
The Array class has a Reverse method that
Reverses the sequence of the elements in the entire one-dimensional Array
Now, the string class has a method that extract the single char elements of the string as an array of chars. At this point the solution is really simple.
Dim strInput = "This is a Test"
Dim c = test.ToCharArray()
Array.Reverse(c)
Dim reversed = new String(c)
Console.WriteLine(reversed)
Or if you like a one liner solution
Dim strInput = "This is a Test"
Dim reversed = new String(strInput.ToCharArray().Reverse().ToArray())
Upvotes: 4
Reputation: 26424
You can use StrReverse:
Dim str As String = "hello"
Dim strRev As String = StrReverse(str) 'olleh
Or this (if you prefer to avoid using VisualBasic namespace):
Dim strRev2 As New String(str.Reverse.ToArray) 'olleh
See also:
Upvotes: 3