2

I am using this function to reverse text but I am having a little issue with speed. for testing I have 130,000 characters text and its taking about 10 seconds. is it possible to speed it up? This questions is different than C# as its a 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
XK8ER
  • 770
  • 1
  • 10
  • 23

5 Answers5

3

Try this:

 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

Source: dot net perls

Cacho Santa
  • 6,668
  • 5
  • 37
  • 70
2

Maybe something along the lines of http://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx? in VB:

Dim TestString As String = "ABCDEFG" 
' Returns "GFEDCBA". 
Dim revString As String = StrReverse(TestString)
Makita
  • 706
  • 5
  • 12
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
Mitch Wheat
  • 288,400
  • 42
  • 452
  • 532
0

I would convert your string to a Character Array, then just call Array.Reverse.

I just tried this and it ran in: 0.862 seconds with a string that had 26,673,152 characters. Granted I'm on a pretyy fast PC but stil.

Jack Marchetti
  • 15,254
  • 13
  • 78
  • 116
-1

As it was said in other answers - it is better to use special function for this: StrReverse

but, if you want to have your own function, you can use this one, it should be faster:

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
Iłya Bursov
  • 21,884
  • 4
  • 31
  • 54