您好我正在尝试在VB.Net中反转字符串而不使用任何内置函数。 这是我的c
Dim word As String
Dim reversed As String
Dim x As String
Dim count As Integer = Len(word)
Function reverse(ByVal value As String) As String
Do
For i = count To 1 Step -1
x = Mid(word, i + 1, 1)
reversed = x
Next
Loop Until count = 1
Return reversed
End Function
Sub Main()
Dim word As String
Console.WriteLine("Enter word")
word = Console.ReadLine()
Console.WriteLine(reverse(word))
Console.ReadLine()
End Sub
但是我的代码无效。有人可以解释我错在哪里吗?
答案 0 :(得分:1)
你的问题看起来像是在这个循环中:
For i = count To 1 Step -1
x = Mid(word, i + 1, 1)
reversed = x
Next
您需要将 x
追加到reversed
,而不是替换它,例如使用
reversed
初始化为空字符串
Dim reversed As String = String.Empty
然后将循环中的行更改为
reversed = String.Concat(reversed, x)
更好的是,StringBuilder
类是理想,可以像你一样重复添加字符串。
答案 1 :(得分:1)
您可以使用 LINQ 扩展程序。
Dim str As String = "Hello World!"
Dim reversed As String = String.Join("", str.Reverse)
Debug.WriteLine(reversed)
如果你想要更多"质朴的"接近:
''' <summary>
''' Reverses the characters of the specified string.
''' </summary>
''' <param name="value">The string to reverse.</param>
''' <returns>the reversed string.</returns>
Public Shared Function Reverse(ByVal value As String) As String
Dim sb As New System.Text.StringBuilder
For Each c As Char In value
sb.Insert(0, c)
Next c
Return sb.ToString
End Function