Reverse a String

By | 2018-01-20

This is a string handling function that that reverse a given string. For example, Good Morning becomes gninroM dooG.

The code reads a string into an array, which is no surprise. We could use a temporary “working” string, or an array to achieve the goal. What is a bit different here is that as the string is read in from the beginning, the values are placed at the back of the array.

The last step is the bring the array back out to a usable string, and return it to the caller.

Private Function ReverseString(ByRef StringToReverse As String) As String

    Dim lngIndex As Long
    Dim ByteArray() As Byte
    Dim tmpByte As Byte
    Dim lngMax As Long

    ByteArray = StrConv(StringToReverse, vbFromUnicode)
    lngMax = Len(StringToReverse) - 1

    For lngIndex = 0 To lngMax \ 2

        tmpByte = ByteArray(lngIndex)
        ByteArray(lngIndex) = ByteArray(lngMax - lngIndex)
        ByteArray(lngMax - lngIndex) = tmpByte

    Next

    ReverseString = StrConv(ByteArray, vbUnicode)

End Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.