加速函数反转字符串

时间:2013-10-17 01:49:09

标签: vb.net

我正在使用此功能来反转文字,但我对速度有点问题。 测试我有130,000个字符文本,大约需要10秒钟。是否有可能加快速度?这个问题与C#不同,因为它是一个vb.net

Function ReverseString(ByRef strString As String) As String
        Dim NextChr, TempString As String, StringLength, Count As Integer, NewString As String = Nothing

        TempString = strString
        StringLength = Len(TempString)
        Do While Count <= StringLength
            Count = Count + 1
            NextChr = Mid(TempString, Count, 1)
            NewString = NextChr & NewString
        Loop
        ReverseString = NewString
End Function

5 个答案:

答案 0 :(得分:3)

试试这个:

 Function Reverse(ByVal value As String) As String
    ' Convert to char array.
    Dim arr() As Char = value.ToCharArray()
    ' Use Array.Reverse function.
    Array.Reverse(arr)
    ' Construct new string.
    Return New String(arr)
    End Function

来源:dot net perls

答案 1 :(得分:2)

也许是http://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx的某些内容? 在VB中:

Dim TestString As String = "ABCDEFG" 
' Returns "GFEDCBA". 
Dim revString As String = StrReverse(TestString)

答案 2 :(得分:2)

Function ReverseString(ByRef strString As String) As String
    Dim charArray As Char() = strString.ToCharArray()
    Array.Reverse(charArray )
    Dim strReversed As New String(charArray )
    ReverseString = strReversed
End Function

答案 3 :(得分:0)

我会将您的字符串转换为字符数组,然后只需调用Array.Reverse

我刚尝试了这个并且它运行:0.862秒,其中一个字符串有26,673,152个字符。虽然我正在使用快速的PC,但仍然很快。

答案 4 :(得分:-1)

正如在其他答案中所说的那样 - 最好使用特殊功能:StrReverse

但是,如果你想拥有自己的功能,你可以使用它,它应该更快:

Function ReverseString(ByRef strString As String) As String
    Dim builder As New System.Text.StringBuilder(strString.Length)
    Dim index As Integer = strString.Length - 1
    While index >= 0
        builder.Append(strString.Chars(index))
        index = index - 1
    End While
    ReverseString = builder.ToString
End Function