我一直试图在最后一小时解决这个问题,我几乎让它起作用,但它只显示了未反转的字样。我不知道为什么会这样。我知道这是一个初学者问题,但请帮忙。感谢。
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
好的,所以我根据kjtl的想法编辑了我的代码,现在我得到一个参数输出范围。我知道这意味着什么,但我不明白为什么我得到这个例外。重申一下,我想尽可能少地编辑此代码以使其工作。这两种想法都是更简单的方法,我只是想修复我的代码,而不是为教育目的而全部替换它。
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
答案 0 :(得分:4)
Array类有Reverse方法
反转整个一维数组中元素的序列
现在,字符串类有一个方法可以将字符串的单个char元素提取为字符数组。此时解决方案非常简单。
Dim strInput = "This is a Test"
Dim c = test.ToCharArray()
Array.Reverse(c)
Dim reversed = new String(c)
Console.WriteLine(reversed)
或者如果您喜欢单线解决方案
Dim strInput = "This is a Test"
Dim reversed = new String(strInput.ToCharArray().Reverse().ToArray())
答案 1 :(得分:3)
您可以使用StrReverse:
Dim str As String = "hello"
Dim strRev As String = StrReverse(str) 'olleh
或者这个(如果你更愿意避免使用VisualBasic命名空间):
Dim strRev2 As New String(str.Reverse.ToArray) 'olleh
另见: